freeCodeCamp Challenge Guide: Sum All Numbers in a Range

freeCodeCamp Challenge Guide: Sum All Numbers in a Range
0

Sum All Numbers in a Range


Problem Explanation

You need to create a program that will take an array of two numbers who are not necessarily in order, and then add not just those numbers but any numbers in between. For example, [3,1] will be the same as 1+2+3 and not just 3+1


Hints

Hint 1

Use Math.max() to find the maximum value of two numbers.

Hint 2

Use Math.min() to find the minimum value of two numbers.

Hint 3

Remember to that you must add all the numbers in between so this would require a way to get those numbers.


Solutions

Solution 1 (Click to Show/Hide)
function sumAll(arr) {
  var max = Math.max(arr[0], arr[1]);
  var min = Math.min(arr[0], arr[1]);
  var temp = 0;
  for (var i = min; i <= max; i++) {
    temp += i;
  }
  return temp;
}

sumAll([1, 4]);

Code Explanation

  • First create a variable to store the max number between two.
  • The same as before for the Smallest number.
  • We create a temporary variable to add the numbers.

Since the numbers might not be always in order, using max() and min() will help organize.

Relevant Links

Solution 2 (Click to Show/Hide)
const sumAll = arr => {
  // Buckle up everything to one!
  const startNum = arr[0];
  const endNum = arr[1];

  // Get the count of numbers between the two numbers by subtracting them and add 1 to the absolute value.
  // ex. There are |1-4| + 1 = 4, (1, 2, 3, 4), 4 numbers between 1 and 4.
  const numCount = Math.abs(startNum - endNum) + 1;

  // Using Arithmetic Progression summing formula
  const sum = ((startNum + endNum) * numCount) / 2;
  return sum;
};

Code Explanation

  • The formula for calculating the sum of a continuous range is “(startNum + endNum) * numCount / 2”.
  • arr[0] and arr[1] can either be startNum or endNum, order doesn’t matter.
  • We can get the count of numbers in range by “Math.abs(arr[0] - arr[1]) + 1”.
  • Applying the formula by plugging in the numbers.

Relevant Links

Solution 3 (Click to Show/Hide)
function sumAll(arr) {
  var sum = 0;
  for (var i = Math.min(...arr); i <= Math.max(...arr); i++) {
    sum += i;
  }
  return sum;
}

sumAll([1, 4]);

Code Explanation

  • Creating a variable sum to store the sum of the elements.
  • Starting iteration of the loop from min element of given array and stopping when it reaches the max element.
  • Using a spread operator (…arr) allows passing the actual array to the function instead of one-by-one elements.

Relevant Links

7 Likes

Quick question: why does the challenge include the reduce method to the helpful links when none of the 3 solutions above use it?

15 Likes

I don’t see any mention or link for the reduce method.

2 Likes

On this page: https://www.freecodecamp.com/challenges/sum-all-numbers-in-a-range

I have:

You don’t?

1 Like

That is the challenge, here are solutions, totally different. If they put reduce as a helpful link then that means it can be used to solve the problem. We just happened to have solutions that don’t use it here. These solutions are originally from multiple campers and not an official hard answer to the challenge, you are free to come up with your own solution as long as it works regardless of what you use.

3 Likes

Thank you @Rafase282 and @P1xt for your replies.

@Rafase282: I thought that you were working hand in hand with those designing the hints. Hence my surprise. But I get your point.

@P1xt: I really like your solution but I struggle to understand your code coming after the return. Would you mind explaining this line step by step for me?

2 Likes

@samuelpath I made most if not all the hints you will see on the on the wiki, the ones on the main site were not done by me. However, FCC is planing on integrating the hints from the wiki into the challenges themselves in the future.

3 Likes

That would be a great move I think.

By the way, I’m really impressed by your Javascript mastery, so kudo ! :raised_hands:

1 Like

I wouldn’t call myself a master at JavaScript, there are many areas that i don’t know or could improve, not directly being on JS. Regardless, thanks!

2 Likes

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…

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

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

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