From:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-numbers-in-a-range
Intermediate Algorithm Scripting: Sum All Numbers in a Range
We'll pass you an array of two numbers. Return the sum of those two numbers plus the sum of all the numbers between them. The lowest number will not always come first.
For example, sumAll([4,1]) should return 10 because sum of all the numbers between 1 and 4 (both inclusive) is 10.
sumAll([1, 4]) should return a number.
sumAll([1, 4]) should return 10.
sumAll([4, 1]) should return 10.
sumAll([5, 10]) should return 45.
sumAll([10, 5]) should return 45.
const sumRange = n => (n * (n+1)) / 2;
const sumAll = arr => sumRange(Math.max(...arr)) - sumRange(Math.min(...arr) - 1);
[
[1, 4],
[4, 1],
[5, 10],
[10, 5]
].forEach(param => console.log(sumAll(param)));
10
10
45
45
No comments:
Post a Comment