gpt4 book ai didi

javascript - 无重复随机化功能

转载 作者:行者123 更新时间:2023-12-03 07:32:08 26 4
gpt4 key购买 nike

函数 rnd_act_select() 正在代码中进一步随机化四个函数,它由我设置的 Photoshop 中的一个按钮调用,一切正常,但我不知道如何设置随机化而不重复案件,直至全部执行完毕。有人可以给我解决这个问题吗?谢谢。

function rnd_act_select() {
// random selection
NumberOfFunctions = 4;//Number of functions in your switch statement.
var ran = Math.floor(Math.random() * NumberOfFunctions);

switch(ran) {
case 0: func_one(); break;
case 1: func_two(); break;
case 2: func_three(); break;
case 3: func_four(); break;
default : return;
}
};


我已经尝试过这种方法,但它不起作用:

function rnd_act_select() {
// random selection begin
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;

// While there remain elements to shuffle...
while (0 !== currentIndex) {

// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;

// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}

return array;
}
var arr = [func_one,func_two,func_three,func_four];
var shuf = shuffle(arr);

switch(shuf) {
case 0: func_one(); break;
case 1: func_two(); break;
case 2: func_three(); break;
case 3: func_four(); break;
default : return;
}
// random selection end
};


如果可能的话,我需要一个明确的答案。谢谢

最佳答案

这应该很容易。为此,您需要记住以前使用过哪些功能。你的算法应该像这样工作:

  1. 创建数组 [0, 1, 2, 3]
  2. Shuffle it .
  3. 按照打乱的顺序运行您的函数。
  4. 当您的随机订单为空时,请从第 1 步开始重复。

关于javascript - 无重复随机化功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35773800/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com