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?
-
No, recursion is not the right method here. Don't overuse recursion when it's not needed.gdoron– gdoron2013年06月02日 06:13:17 +00:00Commented Jun 2, 2013 at 6:13
-
1Do you want to compare the number to all previous used random numbers, or just the last returned random number--ie you never want this new number to return the same number two times in a row.Alan– Alan2013年06月02日 06:14:47 +00:00Commented Jun 2, 2013 at 6:14
-
the latter. I want the function to always show a new value in comparison to the previous one.Emanegux– Emanegux2013年06月02日 06:17:57 +00:00Commented Jun 2, 2013 at 6:17
4 Answers 4
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;
}
8 Comments
previous available outside the function scope. Plus, it would be easier to build several functions calculating random number independently (so last value from some unrelated call would not be treated as your call's last result).Closure way:
var newNumber = (function () {
var previous;
return function () {
var nextValue;
while ((nextValue = Math.floor(Math.random() * 10)) === previous);
previous = nextValue;
return nextValue;
};
})();
1 Comment
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;
}
6 Comments
previous+1 is more :DJust 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);
}
}