Skip to content

Instantly share code, notes, and snippets.

@martin-mok
Created January 10, 2020 00:54
Show Gist options
  • Select an option

  • Save martin-mok/71fcaf28d5cc3d1ac5ffc6d0feda635b to your computer and use it in GitHub Desktop.

Select an option

Save martin-mok/71fcaf28d5cc3d1ac5ffc6d0feda635b to your computer and use it in GitHub Desktop.
sum all numbers in a range

Description

We'll pass you an array of two numbers. Return the sum of those two numbers plus the sum of all the numbers between them. The lowest number will not always come first. For example, sumAll([4,1]) should return 10 because sum of all the numbers between 1 and 4 (both inclusive) is 10.

Tests

tests:
  - text: <code>sumAll([1, 4])</code> should return a number.
    testString: assert(typeof sumAll([1, 4]) === 'number');
  - text: <code>sumAll([1, 4])</code> should return 10.
    testString: assert.deepEqual(sumAll([1, 4]), 10);
  - text: <code>sumAll([4, 1])</code> should return 10.
    testString: assert.deepEqual(sumAll([4, 1]), 10);
  - text: <code>sumAll([5, 10])</code> should return 45.
    testString: assert.deepEqual(sumAll([5, 10]), 45);
  - text: <code>sumAll([10, 5])</code> should return 45.
    testString: assert.deepEqual(sumAll([10, 5]), 45);

Solution

My Soln:

function sumAll(arr) {
  let lowerBound;
  let upperBound;
  let sum=0;
  if(arr[0]<arr[1]){
    upperBound=arr[1];
    lowerBound=arr[0];
  } else{
    upperBound=arr[0];
    lowerBound=arr[1];
  }
  for(let i=lowerBound;i<=upperBound;i++){
    sum+=i;
  }
  return sum;
}

sumAll([1, 4]);

Tidy up:

function sumAll(arr) {
  let biggerNumber = Math.max(...arr);
  let smallerNumber = Math.min(...arr)

  let total = biggerNumber + smallerNumber

  for (let i = smallerNumber + 1; i < biggerNumber; i++) {
    total += i
  }

  return total
}

Other possible solns:
return sum all numbers in a range - stackoverflow
Sum all numbers in a range - codereview.stackexchange

function sumAll(arr) {
  var min = Math.min.apply(null, arr);
  var max = Math.max.apply(null, arr);

  return Array.apply(null, Array(max-min+1))   // get array of correct size
      .map(function(_, b) { return b+min; })   // change it to have correct values
      .reduce(function(a, b) { return a+b; }); // and sum it
}

Here is a problem- What is Array.apply actually doing
See also Array() constructor

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment