I been working on this problem that asks to find the values within the two given inputs. For instance, input: (1,5) yields the result: [1,2,3,4,5]. This problem should give a solution that is done recursively.
Here is the solution that works:
function rangeOfNumbers(startNum, endNum) {
if (endNum - startNum === 0) {
return [startNum];
} else {
var numbers = rangeOfNumbers(startNum, endNum - 1);
numbers.push(endNum);
console.log(numbers);
return numbers;
}
}
The trouble that I am having is understanding how this solution works. I tried debugging through console.log and it looks like values are added like this:
[ 1, 2 ]
[ 1, 2, 3 ]
[ 1, 2, 3, 4 ]
[ 1, 2, 3, 4, 5 ]
If my endNum value is declared as 5 initially and I'm pushing endNum to the end of the array, why doesn't my array look like this: [ 5, 4, 3, 2, 1 ]
What's surprising was when I changed my recursive function to this:
var numbers = rangeOfNumbers(startNum+1, endNum);
numbers.push(startNum);
The array looked like this:
[ 5, 4, 3, 2, 1 ]
Any feedback or clarification on this would be greatly appreciated, thanks!
rangeOfNumbers()) isstartNum = 1, endNum = 1. After your modification, the base case becomesstartNum = 5, endNum = 5.endNuminto the array until after you have constructed the array with all the lower values ofendNumin it first. So you end up pushing1(whenendNum - startNum === 0), then2, then3, then4and finally5.numbersalways starts as[startNum]and the call just before the one that returns[startNum]is the call that hasendNumset to2, in the one before that it is3and so on.endNumin it first. How do the statements execute? Is it something like this:1. rangeOfNumbers(1, 5 - 1)2. rangeOfNumbers(1, 4 - 1)3. rangeOfNumbers(1, 3 - 1)4. rangeOfNumbers(1, 2 - 1)5. rangeOfNumbers(1, 1 - 1)And then my values are pushed starting from statement 5?[1,2,3,4,5]