Reputation: 461
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
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:
Upvotes: 0
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
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