# freeCodeCamp Algorithm Challenge Guide: Sum All Numbers in a Range

freeCodeCamp Algorithm Challenge Guide: Sum All Numbers in a Range
0

#1

Remember to use `Read-Search-Ask` if you get stuck. Try to pair program and write your own code

### 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`

## Hint: 1

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

try to solve the problem now

## Hint: 2

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

try to solve the problem now

## Hint: 3

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

try to solve the problem now

## Basic Code Solution:

``````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.

## Intermediate Code Solution:

``````function sumAll(arr) {
// Buckle up everything to one!

// Using ES6 arrow function (one-liner)
var sortedArr = arr.sort((a,b) => a-b);
var firstNum = arr[0];
var lastNum = arr[1];
// Using Arithmetic Progression summing formula

var sum = (lastNum - firstNum + 1) * (firstNum + lastNum) / 2;
return sum;
}
``````

### Code Explanation:

• Firstly, we create a variable called `sortedArr` which sorts it from the lowest to the highest value.
• `firstNum` is equal to the first number and `lastNum` is equal to the second number.
• Next, using the Arithmetic Progression summing formula we let `sum` equal `(lastNum - firstNum + 1) * (firstNum + lastNum) / 2`.
• Finally, we return `sum`.

The line `var sortedArr = arr.sort((a,b) => a-b);` is probably what will have you more confused. This would be the same as creating a function that returns `a-b` for the `sort()` which is the standard way to sort numbers from smallest to largest. Instead using arrow or fat arrow function, we are able to do all that in one single line thus allowing us to write less.

``````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.

## NOTES FOR CONTRIBUTIONS:

• DO NOT add solutions that are similar to any existing solutions. If you think it is similar but better, then try to merge (or replace) the existing similar solution.
• Categorize the solution in one of the following categories ā Basic, Intermediate and Advanced.

See `Wiki Challenge Solution Template` for reference.

#2

#3

#4

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

#5

I donāt see any mention or link for the reduce method.

#6

I have:

You donāt?

#7

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.

#9

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?

#10

@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.

#11

That would be a great move I think.

By the way, Iām really impressed by your Javascript mastery, so kudo !

#12

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!

#15

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ā¦

#16

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?

#17

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ā¦

#18

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

#19

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

#20

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

#22

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

#23

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!

#24
``````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]);
``````