I know the solution is correct but I just don’t get why. If you look at the comments, that is how I understand the solution. In my head sumAll([1,4]); equals 11 not 10.
geez! that is where I made the error. thanks for pointing out the clear obvious. i feel like an idiot because i have been looking at my notes over and over and scratching my head.
function sumAll(arr) {
var max = Math.max(arr[0], arr[1]);
//max = 4
var min = Math.min(arr[0], arr[1]);
//min = 1
var sum = 0;
for ( var i = min; i <= max; i++) {
// i = 1; 1 <= 4; 1++
// i = 2; 2 <= 4; 2++
// i = 3; 3 <= 4; 3++
// i = 4; 4 <= 4; 4++
sum += i;
// (sum)0 + (i)1 = 1
// (sum)1 + (i)2 = 3
// (sum)3 + (i)3 = 6
// (sum)6 + (i)4 = 10
}
return sum;
}
On a side note, a more performant code would minimise the number of loops and conditional statements.
This problem can easily be solved using a mathematical concept called Arithmetic Progression.
function sumAll(arr) {
var min = Math.min.apply(null, arr);
var max = Math.max.apply(null, arr);
return (max - min + 1) * (min + max) / 2;
}
sumAll([1, 4]);