TheLD
TheLD

Reputation: 2241

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 current code:

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

Pretty simple so far. But how do I prevent func1 (for example) to run twice in a row

Upvotes: 3

Views: 1913

Answers (3)

limekin
limekin

Reputation: 1944

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); 

Upvotes: 0

Wormbo
Wormbo

Reputation: 4992

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.

Upvotes: 0

thefourtheye
thefourtheye

Reputation: 239473

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.

Upvotes: 4

Related Questions