Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

recursive range function not working

I'm trying to teach myself recursion by doing a range function recursively. I can't understand why the code below isn't working?

Iterative version:

function rangeList(num, num2) {
  var arr = [];
  for (var i = num; i < num2; i++) {
    arr.push(i);
  }
  return arr;
}

Recursive version:

function rangeRecursive(num, num2) {
  return (num2 > num) ? rangeRecursive(num2 - 1).concat(num2) : []
}

console.log(rangeList(1, 7)); // returns [1, 2, 3, 4, 5, 6]
console.log(rangeRecursive(1, 7)); // returns [7]
like image 849
alrighty then Avatar asked Sep 24 '15 05:09

alrighty then


People also ask

What is the main problem of a recursive function?

Every time the recursive function is called, it takes up stack space (we'll discuss this more exhaustively in the section) and space for its local variables are set aside. So actually, the recursive version takes up much more space overall than does the iterative version.

What stops a recursive function?

The condition that stops a recursive function from calling itself is known as the base case. In the log function above, the base case is when num is larger than 5 .

What are the limitations of recursion?

Limitations of Recursive Approach:Each function call requires push of return memory address, parameters, returned result,etc. and every function return requires that many pops. 2. Each time you call a function you use up some of your memory allocation may be in stack or heap.


2 Answers

It doesn't work because you are missing a parameter in your recursive call

It should be like this

function rangeRecursive(num, num2) {
  return (num2 >= num) ? rangeRecursive(num /*this was missing*/, num2 - 1).concat(num2) : []
}

Also notice the changed condition on the ternary, otherwise it stops at 1 and doesn't concat it. Either you can use >= or the following

return num2 > num ? rangeRecursive(num, num2 - 1).concat(num2) : [num]
like image 179
JSelser Avatar answered Oct 17 '22 01:10

JSelser


You are missing the parameter in your recursive function. It should be like this:

function rangeRecursive(num, num2) 
{
  return num2 > num ? rangeRecursive(num, num2 - 1).concat(num2) : [num]
}
like image 23
Rahul Tripathi Avatar answered Oct 17 '22 00:10

Rahul Tripathi