Solution for Use Recursion to Create a Range of Numbers

Hi guys,

How do you add a new solution to the answer key?

When comparing my solution to a problem for https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/use-recursion-to-create-a-range-of-numbers

The hints/answers page did not have a similar solution:freeCodeCamp Challenge Guide: Use Recursion to Create a Range of Numbers

I believe my solution is equally elegant as the posted ones and may provide alternative insight to future learners, see below:

function rangeOfNumbers(startNum, endNum) {
      if (startNum == endNum){
              return [endNum];
      } else {
              const arr = rangeOfNumbers(startNum + 1, endNum);
              arr.unshift(startNum);
              return arr;
     }
};
14 Likes

to propose a new solution just open a topic in the #contributors subforum

I have moved your topic there and changed the title so someone will come along to review it

1 Like

Thank you so much! I appreciate the speed of your reply

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

2 Likes

A post was split to a new topic: Using Recursion to Create a Range

Here’s my solution

let arr = [];

function rangeOfNumbers(startNum,endNum) {
  if (endNum-startNum<0){
    return arr;
  }else{
    arr.push(startNum);
    return rangeOfNumbers((startNum+1),endNum);
  
  
  }
};

2 Likes

My Solution is quite similar to the ones given but uses the endNum as an exit condition.

function rangeOfNumbers(startNum, endNum) {
  if(startNum - endNum == 1){
  return [];
  }
   else {
      const newNumber = rangeOfNumbers(startNum, endNum -1);
      newNumber.push(endNum);
      return newNumber;
  }
};
2 Likes

Hi @Citrus!

Welcome to the forum!

If you are interested in contributing a new solution please create a new topic in the #contributors subforum.

For contributions, please wrap your solution within :

[details]
```
code goes here...
```
[/details]

Also, provide all of the necessary code to pass the challenge.

Also, when you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor ( </> ) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

1 Like