Skip to content Skip to sidebar Skip to footer

Call Random Function Javascript, But Not Twice The Same Function

I use a function that randomly selects another function, which works. But sometimes it runs the same function twice or even more often in a row. Is there a way to prevend this? My

Solution 1:

You can simply store the index of the last function called and the next time, get a random number which is not the last seen index, like this

var lastIndex, arr = [func1, func2, func3];

window.setInterval(function() {
    var rand;
    while ((rand = Math.floor(Math.random() * arr.length)) === lastIndex) ;
    arr[(lastIndex = rand)]();
}, 5000);

The while loop is the key here,

while ((rand = Math.floor(Math.random() * arr.length)) === lastIndex) ;

Note: The ; at the end is important, it is to say that the loop has no body.

It will generate a random number and assign it to rand and check if it is equal to lastIndex. If they are the same, the loop will be run again till lastIndex and rand are different.

Then assign the current rand value to the lastIndex variable, because we dont't want the same function to be called consecutively.

Solution 2:

How about a simple check to prevent picking an index that matches the previous pick?

var arr = [func1, func2, func3, ...];
var previousIndex = false;

var pickedIndex;
if (previousIndex === false) { // never picked anything before
  pickedIndex = Math.floor(Math.random() * arr.length);
}
else {
  pickedIndex = Math.floor(Math.random() * (arr.length - 1));
  if (pickedIndex >= previousIndex) pickedIndex += 1;
}
previousIndex = pickedIndex;
arr[pickedIndex]();

This will pick a random function in constant time that is guaranteed to be different from the previous one.

Solution 3:

You can select random values from 0-1. And after every run, swap the recently executed function in the array with the last element in the array i.e. arr[2].

var arr = [func1, func2, func3];
window.setInterval(function(){
    var t, rand = Math.floor(Math.random() * (arr.length-1)),
    randomFunction = arr[rand];
    t = arr[rand], arr[rand] = arr[arr.length-1], arr[arr.length-1] = t;
    randomFunction();
}, 5000); 

Post a Comment for "Call Random Function Javascript, But Not Twice The Same Function"