Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return sum all numbers in a range

function sumAll(arr) {
    var list = [];

    for (var i = arr[0]; i <= arr[1]; i++) {
        list.push(i);
    }

    var total = list.reduce(function(a, b) {
        return a + b;

    });

    return total;
}

sumAll([10, 5]);
//sumAll([1, 4]);  //returns 10
//sumAll([5, 10]); //returns 45
//sumAll([4, 1]);

I need to sum every number in between the given arguments. For sumAll([1, 4]) and sumAll([5, 10]). The code will pass because it creates all numbers in between the two arguments and adding it. However, for sumAll([10, 5]) and sumAll([4, 1]), because the greater number is first argument, I believe it does not run var list. I tried using .sort() method in between so that the numbers are sorted but can't get it to work. How can I use Math.min() and Math.max() for this code to work?

like image 345
jyoon006 Avatar asked Nov 28 '22 14:11

jyoon006


2 Answers

This is one of those times where mathematical equations come in handy. Check out this code:

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

Quite simple logic, right? :)

like image 24
Nigel Avatar answered Dec 05 '22 12:12

Nigel


Easiest way is to use the mathematical formula

1+2+...+n = n(n+1)/2

Here you want the sum,

m+(m+1)+...+n

where m=arr[0] and n=arr[1]. This is equal to the difference

(1+2+...+n) - (1+2+...+(m-1))

which substituting the above formula twice is equal to

n(n+1)/2 - (m-1)m/2

So the correct code is

function sumAll(arr) {
  var min = arr[0];
  var max = arr[1];
  return (max*(max+1) - (min-1)*min)) / 2;
}

Original answer (do not use - left for posterity):

Here's how I'd use Math.min and Math.max to do this:

function sumAll(arr) {
    var list = [];

    var lower = Math.min(arr[0], arr[1]);
    var upper = Math.max(arr[0], arr[1]);

    for (var i = lower; i <= upper; i++) {
        list.push(i);
    }

    var total = list.reduce(function(a, b) {
        return a + b;
    });

    return total;
}

Someone else posted code using arr[0] < arr[0] ? arr[0] : arr[1]; IMO the Math.min and Math.max functions make for more readable code than the ? : operator.

Also, two more cents: I believe it would be simpler to not make a var list at all; instead say var total = 0 and increment it. Like this:

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

    var total = 0;

    for (var i = lower; i <= upper; i++) {
        total += i;
    }

    return total;
}
like image 116
jcarpenter2 Avatar answered Dec 05 '22 13:12

jcarpenter2