0

I was trying to solve a recursion problem that get the integers within a range (x, y).

This takes both negative and positive numbers.

An example of the expected results are:

range(2,9); // => [3,4,5,6,7,8]
range(7,2); // => [6, 5, 4, 3]
range(-9,-4)) // => [-8,-7,-6,-5]

Currently I have the ff:

var range = function(x, y) {

var result = [];

if(x < y){
  for(var i = x+1; i < y; i++){
  result.push(i);
}

return result;
}

if(x > y){
  for(var j = x-1; j > y; j--){
  result.push(j);
}
return result;

}

};

How can I convert my for loops into recursion with the given rules.

5
  • 1
    What have you tried? What specifically do you need help with? Commented Jan 18, 2018 at 1:58
  • a recursion version of my code above.. Commented Jan 18, 2018 at 1:58
  • Ya, that's clear, but what about writing the recursive function do you need help with? This is too broad as is. Commented Jan 18, 2018 at 2:00
  • first how can I convert my for loops into recursion,, Commented Jan 18, 2018 at 2:02
  • 1
    You haven't googled for "convert loops into recursion" have you? Commented Jan 18, 2018 at 2:06

1 Answer 1

2

var range = function (x, y, r = []) {
    const step = x > y ? -1 : 1; // this determines if your range goes up or down
    if(x === y) return [];
    if(x === y - step) return r;
    return r.concat(x + step, range(x + step, y));
}
console.log(range(9,2));
console.log(range(2,9));
console.log(range(9,9))
console.log(range(-7, -15));
console.log(range(-15, -7))

Basic logic is insert x into your array, then concat the range of next x to y, whether it is smaller or bigger than current x

Sign up to request clarification or add additional context in comments.

1 Comment

console.log(range(9,9));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.