Click here to Skip to main content
15,844,607 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
The Task:
Write a recursive function, `range`, that takes a start and an end and returns
an array of all numbers in that range, exclusive. If the end number is less than
the start, return an empty array.


It was my first day with recursion and I found getting the range of 2 numbers easy, however, for me getting the range BETWEEN two numbers took me hours. X.X

This works. But I tried to understand it by logging it and... Well. Impossible, for me.

Again, getting the range was easy but the code broke WITHOUT the else statement and when I changed

else if (startNum <= endNum) 

to
else if (startNum < endNum) {

(To not get the last number aka endNum)


This code is clearly not the ideal answer. Could someone explain what on Earth is going on here/a better solution? I was honestly going to call it quits for the night when I decided to try another else statement and then paste

else {
    console.log("Random Else statement that made it work")
    return range(startNum+1, endNum)
  }


And it, somehow, worked.

What I have tried:

function range(startNum, endNum) {
  if (startNum > endNum) {
    return [];

  } else if (startNum < endNum) { 
    console.log(range(startNum+1, endNum))
    var rangeArray = range(startNum+1, endNum);

    console.log(startNum + " <-- Start  End ---> " + endNum)
    rangeArray.unshift(startNum);
    return rangeArray;

  } else {
    console.log("Random Else statement that made it work")
    return range(startNum+1, endNum)
  }
};
Posted
Updated 10-Oct-22 2:27am
v2
Comments
Gerry Schmitz 10-Oct-22 12:16pm    
You want the numbers "between"; you were / are missing the case where startNum + 1 == endNum (i.e. no numbers in between). Your "else" handles the case where startNum == endNum.
Chris Aug2022 10-Oct-22 21:46pm    
Awesome, I wke up this morning and had an 'aha duh' moment. Would you like to provide a solution so I can accept it?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900