Hello, I just solved the sum all numbers in a range challenge but I got a strange behavior in the process
I first did this…
var total = 0;
function sumAll(arr) {
var min = Math.min.apply(null, arr);
var max = Math.max.apply(null, arr);
for(var i = min; i <= max; i++){
total += i;
}
return total;
}
sumAll([5, 10]);
only the first test that checks if the output is a number passed, though the outputs were correct. However, when I did the following, which is basically changing the scope of the total variable, it was accepted
function sumAll(arr) {
var min = Math.min.apply(null, arr);
var max = Math.max.apply(null, arr);
var total = 0;
for(var i = min; i <= max; i++){
total += i;
}
return total;
}
sumAll([5, 10]);
WHY???
This is what I did. It works.
function sumAll(arr) {
var sum = 0;
if(arr[1]>arr[0]){
for(var i = arr[0]; i <= arr[1]; i++){
sum = sum + i;
}
}
else{
for(var j = arr[0]; j >= arr[1]; j--){
sum = sum + j;
}
}
return sum;
}
sumAll([4, 1]);
congrats.I will try with this later.
I am wandering if there is a way to create the numbers without using for.....
I mean for example using map. Because as I understood map method return an array with the same input length.....
function sumAll(arr) {
let data = ([].concat(arr)).sort((a,b)=>a-b);
let newData = []
for (let i = data[0];i<=data[1];i++){
newData.push(i)
}
return(newData.reduce((a,b)=>a +b));
}
sumAll([1, 4]);
There is also a mathematical formula for adding all numbers from X to Y, which is very useful here, and lets you avoid a for loop completely.
(highestNumber - lowestNumber + 1) * (highestNumber + lowestNumber) / 2
aww wow… that’s genius i understood ur solution perfectly. good job!