Getting range numbers using recursion in JavaScript

江枫思渺然 提交于 2021-02-16 20:33:32

问题


I am trying to get the range of numbers using recursion. Can someone explain to me why it isn't working?

function range(x,y){
    var results = [];
    if(x === y){
        return results;
    }



return  results.push(range(x + 1,y));
}

range(1,5);

回答1:


Try this:

function rangeOfNumbers(startNum, endNum) {
 if (startNum - endNum === 0) {
  return [startNum];
 } else {
  const numbers = rangeOfNumbers(startNum + 1, endNum);    
  numbers.unshift(startNum);
  return numbers;
 }
};



回答2:


The beauty of recursion is that you don't need local variables (var results). You just pass state as arguments to each recursive iteration:

const concat = (xs, y) => xs.concat(y);

const range = (x, y) => {
  const rec = (x, y, acc) => x < y ? rec(x + 1, y, concat(acc, x)) : acc;
  return rec(x, y, []);
}

ES5 version in case you aren't familiar with the arrow syntax:

function concat(xs, y) {
  return xs.concat(y);
}

function range(x, y) {
  function rec(x, y, acc) {
    return x < y ? rec(x + 1, y, concat(acc, x)) : acc;
  }

  return rec(x, y, []);
}

That isn't the most elegant solution though!

With recursion we can simply build up the stack with each recursive call. Each stack frame contains a computed partial result. Then we just need to unwind the stack and attach each partial result to an array:

const range = (x, y) => x < y ? [x].concat(range(x + 1, y)) : [];

Or more functional:

const concat = (xs, y) => xs.concat(y);
const range = (x, y) => x < y ? concat([x], range(x + 1, y)) : [];

Note that concat([x], range(x + 1, y)) is the recursive case and [] the base case.




回答3:


Results will be always empty since you actually don't put anything in it.

What would work is this

function range(x,y){
    var results = [];
    if(x === y){
        return results;
    }
    results.push(x);
return  results.concat(range(x + 1,y));
}

range(1,5);



回答4:


Solution: Solved this recursion problem, which is taking 2 numbers as input and returning back the array which contains range of the numbers inclusive of the startNumber and EndNumber

Assumption-> end_num is always greater than start_num

function rangeOfNumbers(start_num, end_num) {
    if(start_num!==end_num){
        let numbers = rangeOfNumbers(start_num+1,end_num);
        numbers.unshift(start_num);
        return numbers;
    }
    else
        return [start_num];
    };


来源:https://stackoverflow.com/questions/38175342/getting-range-numbers-using-recursion-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!