Home > Mobile >  Double countdown using recursion function?
Double countdown using recursion function?

Time:04-13

I'm trying to write a recursion using JavaScript, without using global variables but i am not sure that the program can be possible like desire output.

Question is "Given a non-negative integer n, create a double countdown-pattern in the output." Example: If you ran doubleCountdown(5) you would also get the following output:

5
4
3
2
1
4
3
2
1
0

I have tried following ways: In this way getting down to up output but not exact output:

double_countdown(5);
function double_countdown(n){
    if(n == 0){
        console.log(n);
        return
    }
    console.log(n);
    double_countdown(n-1);
    console.log(n);
}

In this ways, i have used global for desired output but not standard way.

let second_n = 0;
let double_count =0;
double_countdown(5);
function double_countdown(n){
    if(n == 0 && double_count == 0){
        double_count = 1;
        double_countdown(second_n-1);
        console.log(n);
    }
    if(n == 0){
        return
    }else{
        second_n  =1;
    }
    console.log(n);
    double_countdown(n-1);
}

CodePudding user response:

Implement the recursive function in a way that it keeps track of its recursion state by providing and working with more parameters than just the required first parameter (which is the current count down value).

Thus one would implement e.g. a function which is capable of running the count down cycle N times. And a double_countdown respectively countDownTwice function could be derived from such a generic implementation.

function countDownNTimes(value = 0, times = 1, initialValue) {
  // initially invoked with an `undefined` value for `initialValue`.
  initialValue ??= value;

  if (times >= 1) {
    console.log(value);

    if (value <= 0) {
      // does trigger a new recursion cycle.
      countDownNTimes(initialValue, --times, initialValue);
    } else {
      // stays within the current recursion.
      countDownNTimes(--value, times, initialValue);
    }
  }
}
const countDownTwice = value => countDownNTimes(value, 2);

console.log('... countDownTwice(5) ...');
countDownTwice(5);

console.log('... countDownNTimes(2, 3) ...');
countDownNTimes(2, 3);
.as-console-wrapper { min-height: 100%!important; top: 0; }

CodePudding user response:

Finally, after trying many times. I got the answer. If anything wrong then please help for more improve.

double_countdown(5);
function double_countdown(n,sc=0){
    if(sc == 0) sc = n;
    if(n == 0 ) return ;
    console.log(n);
    double_countdown(n-1,sc);
    console.log(sc-n);
}

  • Related