Home > Software engineering >  Recursion better understanding
Recursion better understanding

Time:10-02

https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/use-recursion-to-create-a-countdown

We have defined a function called countdown with one parameter (n). The function should use recursion to return an array containing the integers n through 1 based on the n parameter. If the function is called with a number less than 1, the function should return an empty array. For example, calling this function with n = 5 should return the array [5, 4, 3, 2, 1]. Your function must use recursion by calling itself and must not use loops of any kind.

    // Only change code below this line
   

     function countdown(n){
          if (n<1)
          return [];
          else{
            const numbArray = countdown(n-1);
            numbArray.push(n)
            return numbArray;
          }
        }
        console.log(countdown(5))
    // Only change code above this line

comes out like [1 2 3 4 5] instead of [5 4 3 2 1]

I've been breaking my mind forever then I have completed it with the unshift method but felt like it wanted to me use push even though that sends data to the end of the stack

CodePudding user response:

 function countdown(max,currentN){
      if (currentN > max)
      return [];
      else if(currentN <= max){
   const numbArray = countdown(max,currentN 1);
        numbArray.push(currentN)
        return numbArray;
      }
    }
    console.log(countdown(5,1))
// Only change code above this line

basically it just counts up to the end value given at start

CodePudding user response:

else {
 const arr = []
 arr.push(n)
 return arr.concat(countdown(n-1))
}

you can use this code replace, y question reason is y not understand recursion, try to break the point and watch the function execution step by step in the browser or vscode

  • Related