3

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

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Awesome! Thank you, quick response and easy implementation!
While technically correct, this solution has a chance to spin the loop for a few times if the random value happoens to be the same again.
0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.