Eloquent JavaScript - something I didn't understand in the book (first edition)

Eloquent JavaScript - something I didn’t understand in the book (first edition):

In page 61, there is the code:

function sum(numbers) {
    var total = 0;
    for (var i = 0; i < numbers.length; i++) {
        total += numbers[i];
   return total;
}

sum(range(1, 10));
-> 55

Why is it 55?

How did we reach 55 from a range of 1,10 (some number between 2-9)?

Thanks

1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = ?

3 Likes

Hmm, but why is it 1+2+3+4+5+6+7+8+9+10 and not 2+3+4+5+6+7+8+9 (which are between 1 and 10)?

I mean, as far as I know, the range concept referrers to what come between the numbers of the rage, so this is what I miss.

Because that is what the range method says to do…
It says to start with 1 and go up to and equal to the second argument.

Here is the solution from https://eloquentjavascript.net/code/#4.1

function range(start, end, step) {
  if (step == null) step = 1;
  var array = [];

  if (step > 0) {
    for (var i = start; i <= end; i += step)
      array.push(i);
  } else {
    for (var i = start; i >= end; i += step)
      array.push(i);
  }
  return array;
}

function sum(array) {
  var total = 0;
  for (var i = 0; i < array.length; i++)
    total += array[i];
  return total;
}

Edited: Didn’t really like the gist I linked to before (this is cleaner).

1 Like

This is what you missed (emphasis mine)

source https://eloquentjavascript.net/04_data.html

I’m glad that you mentioned that, for I was about to bring up the formula n * (n+1) / 2 to calculate the sum from 1 to n.

Why does that work? Start with a set S of number from 1 to n
S = 1 + 2 + ... + (n - 1) + n

Reverse the set
S = n + (n - 1) + ... + 2 + 1

Add them together
S = 1 + 2 + ... + (n - 1) + n S = n + (n - 1) + ... + 2 + 1 2S = (1+n) + (2 + n-1) + ... + (n-1 + 2) + (n + 1)

Those all add to the same value
2S = (n+1) + (n+1) + ... + (n+1) + (n+1)

And there are n of them
2S = n(n+1)

So the total sum of the numbers from 1 to n is:
S = n(n+1)/2

2 Likes

Just to put this into layman’s terms, if you choose to setup range to not include the start number (you shouldn’t), you would end up with

2, 3, 4, 5, 6, 7, 8, 9, 10 for range(1, 10)

Reverse that, and try range(10, 1), you end up with
9, 8, 7, 6, 5, 4, 3, 2, 1

See the difference? You could get two different sums for the same range values. You include both the end and start to ensure consistency.

The start and end numbers should always be inclusive, unless otherwise specified.

Agreed, was simply pointing out what would happen if you didn’t do that. It produces inconsistent results when using the same range parameters but from ascending to descending.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.