gpt4 book ai didi

javascript - 如何随机化 JavaScript 数组并确保顺序项不相同

转载 作者:行者123 更新时间:2023-12-02 19:02:29 24 4
gpt4 key购买 nike

我有一系列问题,其中一些问题可能是相同的。

 {"choice":"attributes","text":"Happy"},
{"choice":"attributes","text":"Fun"},
{"choice":"attributes","text":"Enjoyable"},
{"choice":"attributes","text":"Pleasurable"},
{"choice":"attributes","text":"Ecstatic"},
{"choice":"attributes","text":"Sad"},
{"choice":"attributes","text":"Tedious"},
{"choice":"attributes","text":"Annoying"},
{"choice":"attributes","text":"Depressing"},
{"choice":"attributes","text":"Unhappy"},
{"choice":"attributes","text":"Happy"},
{"choice":"attributes","text":"Fun"},
{"choice":"attributes","text":"Enjoyable"},

目前,我正在使用 FisherYatesShuffle() 对数组进行随机化,但我真正需要做的是在随机播放之后遍历列表并确保没有两个连续项目是相同的,知道吗?

例如我们永远得不到

{"choice":"attributes","text":"Happy"},
{"choice":"attributes","text":"Happy"},

编辑以澄清一些问题。数组中的所有项目都必须保留。

最佳答案

不断打乱数组,直到没有两个相同的连续项:

var shuffled = false,
i = 0,
length = myArray.length,
previous;
while(!shuffled){ // repeat this until we have a shuffled array.
myArray = FisherYatesShuffle(myArray); // (Assuming you have that function)
shuffled = true; // first, assume the array is shuffled,
for(i = 0; i < length && shuffled; i++){ // Then loop through the array to check if it is indeed shuffled.
if(previous && previous.text == myArray[i].text){
shuffled = false; // If it isn't shuffled, set shuffled to false.
} // This breaks the for loop, and tries to shuffle the array again.
previous = myArray[i];
}
}

优点是它只洗牌一次,如果循环第一次被证明充分洗牌,但如果有很多相同的项目,它可以经常迭代循环,因为它必须随机返回来自 FisherYatesShuffle 的经过正确洗牌的数组。

关于javascript - 如何随机化 JavaScript 数组并确保顺序项不相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14648736/

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