spaceDog
spaceDog

Reputation: 461

Javascript Recursion?

I am practicing recursion. Conceptually I understand how this should work, (see below) but my code isn't working.

Please tell me what I am doing wrong. And please explain each step of your code and how it works. Clear Explanation is ten times better than just giving me code that works.

  /*
  buildList(0, 5) ==  buildList(0, 5 - 1) // [0]
  buildList(0, 4) ==  buildList(0, 4 - 1) // [0,0]
  buildList(0, 3) ==  buildList(0, 3 - 1) // [0,0,0]
  buildList(0, 2) ==  buildList(0, 2 - 1) // [0,0,0,0]
  buildList(0, 1) ==  buildList(0, 1 - 1) // [0,0,0,0,0]
  */

var buildList = function(value, length) {
    var result = [];
   if (length === 0) {
    return result;
   }

   result.push(value);

   return  buildList(result.push(value), length - 1);

};


buildList(0, 5);

I understand how recursion works on a conceptual level.

Upvotes: 1

Views: 821

Answers (3)

Daniel Patrick
Daniel Patrick

Reputation: 4340

  /*
  buildList(0, 5) ==  buildList(0, 5 - 1) // [0]
  buildList(0, 4) ==  buildList(0, 4 - 1) // [0,0]
  buildList(0, 3) ==  buildList(0, 3 - 1) // [0,0,0]
  buildList(0, 2) ==  buildList(0, 2 - 1) // [0,0,0,0]
  buildList(0, 1) ==  buildList(0, 1 - 1) // [0,0,0,0,0]
  */

var result = []; //(1)

var buildList = function(value, length) {
   if (length === 0) {
    return result;
   }

   result.push(value);

   return  buildList(value, length - 1);  //(2)

};


buildList(0, 5);

You're doing two things wrong:

  1. You're initializing result inside the method. This means every time the recursive method call is made, you're resetting result to an empty array.
  2. You're passing the array into the recursive call of buildlist(). You want to be passing the value in there.

Upvotes: 0

Oriol
Oriol

Reputation: 288680

Your approach can't work, because the base case returns a new empty array, and other cases return the result of the recursion.

Instead, you should first recurse and then push

var buildList = function(value, length) {
  if (length <= 0) return [];
  var recur = buildList(value, length-1);
  recur.push(value);
  return recur;
};

Alternatively, in the base case you can avoid creating a new array

var buildList = function(value, length, array=[]) {
  if (length <= 0) return array;
  array.push(value);
  return buildList(value, length-1, array);
};

Upvotes: 2

Tudor Constantin
Tudor Constantin

Reputation: 26871

The problem is that with every call to your function, the result variable gets reinitialized to []. If you declare that variable outside your function, the code works:

var result = [];
var buildList = function(value, length) {

   if(length === 0){
    return result;
   }

   result.push(value);

   return  buildList(result.push(value), length - 1);

};


buildList(0, 5);
console.log(result);

Upvotes: 0

Related Questions