1
votes

This is part of a much bigger algorithm problem that I am trying to solve.

I am trying to create an array of all numbers less than num.

Here is my Code:

function sum(num, arr = []) {
  if (num == 0) {
    return arr;
  }

  arr.push(num);

  return sum(num - 1);
}

console.log(sum(10));

I tried declaring arr as a variable and as an argument. I can’t see why it returns an empty array.

How can I fix the array so that it doesn’t return an empty array?


The broader question if you are interested is:

In number theory and combinatorics, a partition of a positive integer n, also called an integer partition, is a way of writing n as a sum of positive integers. Two sums that differ only in the order of their summands are considered the same partition. If order matters, the sum becomes a composition. For example, 4 can be partitioned in five distinct ways:

4
3 + 1
2 + 2
2 + 1 + 1
1 + 1 + 1 + 1
2

2 Answers

3
votes

The problem with your first snippet is that you don't pass arr into sum. If you do, you get the array:

function sum(num, arr = []) {
  if (num == 0) {
    return arr;
  }

  arr.push(num);
  return sum(num - 1, arr);
  //                  ^^^−−−−−−−−−−−−−−−−−−−−−−−−
}


console.log(sum(10));
2
votes

It returns empty array because you did not send in the second parameter, which is arr, hence each recursion is initialized with an empty array.

function sum(num, arr = []) {
  if (num == 0) {
    return arr;
  }
  arr.push(num);
  return sum(num - 1, arr);
}
console.log(sum(10));