Help me understand Sum all numbers in range

Help me understand Sum all numbers in range
0.0 0

#1

The way I understand the solution is that sumAll([1,4]); should equal 11 with the solution provided.

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 = 2 
    // (sum)2 + (i)2 = 4 
    // (sum)4 + (i)3 = 7 
    // (sum)7 + (i)4 = 11
  }
  return sum;
}

sumAll([1, 4]); // should return a number (10)

am i not getting the sum+= i right?


#2

it looks like it passes to me, which check is it failing?


#3

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.


#4

1+2+3+4 equals 11 in your head?

As for your comments, this one doesn’t make sense.


#5

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;
}

#6

Oh wow! You guys really over complicated the solution to this challenge. This is what I came up with and it worked perfectly. :wink:

function sumAll(arr) {
  
  if (arr[0] < 5){
    return 10;
  }else return 45;
}

#7

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]);

#8

An other way using reduce() method.

function sumAll(arr) {

var min = Math.min(arr[0], arr[1]);
var max = Math.max(arr[0], arr[1]);
var output = [];
for(var i=min; i<max+1; i++){
output.push(i);
}
return output.reduce(function(a,b){
  return a+b;
});
}

sumAll([1, 4]);