Reputation: 1120
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?
Upvotes: 3
Views: 280
Reputation: 700192
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;
}
Upvotes: 3
Reputation: 150253
Closure way:
var newNumber = (function () {
var previous;
return function () {
var nextValue;
while ((nextValue = Math.floor(Math.random() * 10)) === previous);
previous = nextValue;
return nextValue;
};
})();
Upvotes: 3
Reputation: 83358
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;
}
Upvotes: 7
Reputation: 1952
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);
}
}
Upvotes: 1