简体   繁体   中英

Simple Recursion in Javascript

I want to write a function that checks if a random number is equal to a previous random number and returns a new random number not equal to the previous one. I want to use recursion to do this but I'm not sure if this is the correct syntax.

function newNumber(next,previous) {
    if (next != previous)
        return next;
    else {
        next = Math.floor(Math.random()*10);
        newNumber(next, previous);
    }
}

What would be the best way to get this to work?

I would ditch the recursion for this altogether. Just store the last random number as a property of the function itself, and the next time the user wants a random number, just return the first one you compute that's different from the last one.

Something like -

function newNumber() {
    var nextValue;
    while ((nextValue = Math.floor(Math.random()*10)) === newNumber.previous) ;

    newNumber.previous = nextValue;
    return nextValue;
}

Closure way:

var newNumber = (function () {
    var previous;

    return function () {
        var nextValue;
        while ((nextValue = Math.floor(Math.random() * 10)) === previous);

        previous = nextValue;
        return nextValue;
    };
})();

Fiddle

You don't need recursion for that. Actually you don't even need a loop. Just pick a random number from the numbers that are not the previous number:

function newNumber(previous) {
  var next = Math.floor(Math.random()*9);
  if (next >= previous) next++;
  return next;
}

Just add return to newNumber(next, previous); in else block. The code goes like this now:

function newNumber(next,previous) {
    if (next != previous)
        return next;
    else {
        next = Math.floor(Math.random()*10);
        return newNumber(next, previous);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM