最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Use Recursion to Create a CountdownPassed (JS Algorithm) - Stack Overflow

programmeradmin0浏览0评论

Question

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.

function countdown(n, newArr = []){
   
    if(n == 1){
    return newArr;
  }
    newArr.push(n);
    return countdown(n - 1)
  }


console.log(countdown(5));

Question

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.

function countdown(n, newArr = []){
   
    if(n == 1){
    return newArr;
  }
    newArr.push(n);
    return countdown(n - 1)
  }


console.log(countdown(5));

My Question

Is there a way to fix this code so that it works?

I can provide an alternative solution, but I do not understand it:

function countdown(n) {
  if (n < 1) {
    return [];
  } else {
    const arr = countdown(n - 1);
    arr.unshift(n);
    return arr;
  }
}

Share Improve this question asked May 3, 2020 at 8:52 AndrewNeedsHelpAndrewNeedsHelp 4155 silver badges16 bronze badges 7
  • 2 pass on newArr. – Jonas Wilms Commented May 3, 2020 at 8:54
  • what does this mean? – AndrewNeedsHelp Commented May 3, 2020 at 8:56
  • 1 In your recursive call, you only pass on n. For newArr the default parameter is taken, so you create a new array on every recursive step. – Jonas Wilms Commented May 3, 2020 at 8:57
  • function countdown(n, newArr = []){ if(n == 1){ return newArr; } newArr.push(n); return countdown((n - 1), newArr) } console.log(countdown(5)); (tried this) – AndrewNeedsHelp Commented May 3, 2020 at 8:59
  • 1 the first version should work, so whats wrong with it? – Jonas Wilms Commented May 3, 2020 at 9:18
 |  Show 2 more ments

4 Answers 4

Reset to default 4

The problem is that you do not pass on the array to the recursive call, so each recursive execution creates a new, empty array. As a consequence, it does not return the array that had a value pushed to it, but the new, empty one that is ing back from the recursive calls.

Secondly, you never push value 1 to the array. So it would be better to stop the recursion at 0 instead of 1.

So taking those two fixes, you get this:

function countdown(n, newArr=[]) {
    if (n <= 0) {
        return newArr;
    }
    newArr.push(n);
    return countdown(n - 1, newArr)
}

console.log(countdown(5));

Your alternative solution is clean, because it does not need to pass an array as argument. It uses the returned array to add the next value to it (in front of it). It would have my preference.

To understand how it works, print out the intermediate values:

function countdown(n) {
  if (n < 1) {
    console.log("At the end of recursion. Creating and returning an empty array.");
    return [];
  } else {
    const arr = countdown(n - 1);
    console.log("Got the following array back from the recursive call:");
    console.log(JSON.stringify(arr));
    arr.unshift(n);
    console.log("Prefixing it with " + n + " and returning the result:");
    console.log(JSON.stringify(arr));
    return arr;
  }
}

var result = countdown(5);

You need to hand over the result array for the recursive call. And you need to check if no value is left, ten return the result array.

function countdown(n, result = []) {
    if (n < 1) return result;
    result.push(n);
    return countdown(n - 1, result);
}

console.log(countdown(5));

As another approach, you could return an array and for the exit condition take the final value, otherwise take n and the spreaded result of the recursive call.

function countdown(n) {
    if (n < 1) return [];
    return [n, ...countdown(n - 1)];
}

console.log(countdown(5));

yes, you can modify your solution like that

function countdown(n){
       
        if(n == 0){
        // stop the function at 0 so it will not be included in the array
        return [];
      }
      
        // concat the value of n as an array with the value less than it
        return [n].concat(countdown(n - 1))
      }
    
    
    console.log(countdown(5));

the problem in your solution is that your array initialized as an empty array every time so the final answer will be an empty array

At this point we will create the countdown function which call itself and called recursion.

function countdown(n) {
    if (n < 1) {
        return [];
    } else {
        console.log(n, "before calling");
        const arr = countdown(n - 1);
        console.log(n, "after calling");
        return arr;
    }
}
console.log(countdown(5));

And now when we know that the "before calling" is place where n is decrease and the "after calling" is place where n is increase, based on that we can do this.

const arr = [];
function countdown(n) {
  if (n < 1) {
    return arr;
  } else {
    arr.push(n);
    return countdown(n - 1);;
  }
}
console.log(countdown(5));

发布评论

评论列表(0)

  1. 暂无评论