简体   繁体   English

调用随机函数Javascript,但不是两次相同的函数

[英]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 但是如何阻止func1(例如)连续运行两次

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循环是关键,

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 . 它将生成一个随机数并将其分配给rand并检查它是否等于lastIndex If they are the same, the loop will be run again till lastIndex and rand are different. 如果它们相同,则循环将再次运行,直到lastIndexrand不同。

Then assign the current rand value to the lastIndex variable, because we dont't want the same function to be called consecutively. 然后将当前rand值赋给lastIndex变量,因为我们不希望连续调用相同的函数。

You can select random values from 0-1. 您可以从0-1中选择随机值。 And after every run, swap the recently executed function in the array with the last element in the array ie arr[2]. 并且在每次运行之后,将数组中最近执行的函数与数组中的最后一个元素交换,即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); 

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. 这将在恒定时间内选择随机函数,该函数保证与前一个函数不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM