freeCodeCamp Challenge Guide: Sum All Numbers in a Range

Agreed… I spent hours trying use the reduce method, to no avail in combination with a loop…

It should not be there; it was misleading…

7 Likes

I made a crude code for this challenge https://jsfiddle.net/nfhqrh5y/

It gives all output (1,4 > 10, 4,1 > 10, 5,10 > 45 etc) when checking with fiddle.

However, when i paste this code into FCC challenge wont pass.

Ofc im replacing console.log(m) with return m; when pasting so this might not be the problem.

I am aware there are more elegant solutions but want to know why this one is not passable?

Oh i see. I created function with (value, value) type of argument whereas at FCC script is awaiting for ([value, value]), array kind of argument.

Once I devise function to function sumAll(arr)

var min;
var max;
min = arr[0];
max = arr[1];

challenge passed.
Okay i think ill check other solutions as well now…

Refactored code to suit Math.max()
https://jsfiddle.net/dvezv801/

I used .reduce() in my solution:

function sumAll(arr) {
    arr = arr.sort((a, b) => a - b);
    var count = arr[1] - arr[0] + 1;
    
    return Array
        
        // create empty array of length = 'count'
        .apply(null, new Array(count))
        
        // populate with values from input array range
        .map((num, ind) => arr[0] + ind)
        
        // sum all the values in the range
        .reduce(function (accum, curval) {
            return accum + curval;
        });
}
6 Likes

I used the below after reading about Arithmetic Progression. Interested in anyone’s thoughts. It ignores the use of any array related work and just sticks to the math aspect of the question.

function sumAll (arr) {
    const min = Math.min(...arr);
    const max = Math.max(...arr);
    return (((max - min + 1) * (min + max)) / (2));
}
13 Likes

damn man i did this

function sumAll(arr) {
  var a=[];
  var b;
  if(arr[0]<arr[1]){
    b=arr[0];
  for(var i=arr[0];i<arr[1]-1;i++){
     
     a.push(b);
     b=++arr[0];
     
  }
  }else{
    b=arr[1];
     for(var j=arr[1];j<(arr[0]-1);j++){ 
     a.push(b);
     b=++arr[1];
  }
}
   arr=a.concat(arr);
    var sum = arr.reduce(function(a, b) {
  return a + b;
}, 0);
   return sum;
}

sumAll([5, 10]);
1 Like

Hey, yeah well I’ve pretty much the same as P1xt already wrote above, which in turn pretty much resembles your code. The solution is pretty elegant. It’s actually just a transformation of basic arithmetic math (Gauß). Don’t get me wrong, I also spent quite some time until I figured it out. But the more thrilling insight for me is how valuable good old math is when it comes to solving problems with code! So good work!

1 Like
function sumAll(arr) {
  var sum = 0;
  arr[0] > arr[1] && arr.reverse();
  for (i = arr[0]; i <= arr[1]; sum += i++);
  return sum;
}

sumAll([1, 4]);
8 Likes

Intermediate Solution states:

But is this true? Calling arr.sort() actually sorts the array in place, does it not? The variable sortedArr is initialized but never used–the original arr is used instead.

What I’m driving at is the sortedArr variable is extraneous and doesn’t need to be declared.

3 Likes

Can someone tell me how ineffective / effective my recursive solution is:

function sumAll(arr) {
  var min = Math.min(arr[0], arr[1]),
      max = Math.max(arr[0], arr[1]);
  
  if (min === max)
    return (min);
  return max + sumAll([min, max - 1]);
}

sumAll([1, 4]);

And generally, how can one measure code efficiency in js ?

Cheers!

8 Likes

en… why is no one using Math.abs()?

function sumAll(arr) {
  return (arr[0]+arr[1])*(Math.abs(arr[0]-arr[1])+1)/2;
}
9 Likes

My solution is similar, except instead of using the newer spread syntax, I opted for the classical apply function.

function sumAll(arr) {
  var n1 = Math.min.apply(null, arr);
  var n2 = Math.max.apply(null, arr);
  return ((n2 + n1) * (n2 - n1 + 1)) / 2;
}
3 Likes

I also thought the reduce method should be used. I agree the code examples here without it are simpler hence a good practice. But it was fun learning more about the reduce method:

function sumAll(arr) {
var newArr = [];
newArr[0] = Math.min(…arr);
var i = Math.min(…arr);
var j=0;

while (i<Math.max(arr[0],arr[1])){
newArr[++j] = ++i;
}
return newArr.reduce(function(acc, val){
return acc + val;
},0);
}

This is my solution :

function sumAll(arr) {
var max = Math.max(arr[0], arr[1]);
var min = Math.min(arr[0], arr[1]);
var newArr = [];

for (i=min; i<=max; i++) {
newArr.push(i);
}
return newArr.reduce(function(a, b) {
return a + b;
});
}

sumAll([5, 10]);

This is my code for this freecodecamp exercise:

I used reduce and it helped a lot.

function sumAll(arr) {

var max = arr.reduce(function(a, b) {
  return Math.max(a, b);
});
var min = arr.reduce(function(a, b) {
  return Math.min(a, b);
});
var temp = 0;

for(var i = min; i < max + 1; i++) {
  temp += i;
  console.log(temp);
}
return temp;

}

sumAll([4, 1]);

You are not alone :smiley: Look at mine :smiley:

1 Like

My solution:

function sumAll(arr) {
  //sort array so lowest comes first
  arr.sort(function(a,b){
    return b < a;
  });
  
  //create sum variable and assyign total sum of arr to it
  var sum = arr.reduce(function(acc, num){
    return acc + num;
  });
  //check if we need to add the sum of number between first and last element of an array
  if(arr[0] !== arr[1]){
    //create second array to store numbers between first and last element of an array
    var arr2 = [];
    var index = arr[0]+1;//set the index
    
    while(index < arr[1]){
      arr2.push(index);//add between numbers to arr2
      index++;
    }
    //assyign sum of arr to sum of arr2
    sum += arr2.reduce(function(acc, num){
      return acc + num;
    });
  }
  
  return sum;
}
//test
sumAll([1, 4]);

Here I am my code using the .sort method and a for loop.

function sumAll(arr) {
var sumArr = 0, sortArr = arr.sort(function(a,b){
return a - b;
});
for(var i = sortArr[0]; i < sortArr[1]; i += 2){
sumArr += i + (i + 1);
}
return sumArr;
}

sumAll([10, 5]);

But sincerely , if the suggestion to using reduce() is for learning then solution should include it. Remember its a leanring environment . As one who teaches at a university I cannot give my students a hint then not use it. It causes confusion and frustrates learners.