gpt4 book ai didi

javascript - 从 JS 数组中选择一个值并跳过它,直到显示所有值

转载 作者:太空宇宙 更新时间:2023-11-04 03:15:37 24 4
gpt4 key购买 nike

我有一个由 6 个值组成的数组。我正在运行 Math.random 来对其进行洗牌。但是,它每次都会对数组进行洗牌并显示重复的值。我想对数组进行洗牌并获得 1 个唯一值。应从数组中删除该值,直到获取所有其他值为止。例如,如果一个数组包含项目 1,2,3,4,并且在对其进行洗牌后,答案是 3。现在,我希望它排除 3 并从 1,2,4 中获取新值。


const params = {
icon_emoji: ':laughing:'
};
var members=['1','2','3','4','5','6','7'];
var assignee = members[Math.floor(Math.random()*members.length)];

bot.postMessageToChannel('general', `It's ${assignee}'s turn today!`, params);


}

function results() {


const params = {
icon_emoji: ':laughing:'
};
bot.postMessageToChannel('general', `Inside results`, params);


}

最佳答案

您对“洗牌”的定义不正确...与其从数组中随机选择项目然后将它们从数组中拼接出来,为什么不实际上使用Fisher-Yates shuffle对整个数组进行洗牌(即以随机顺序重新排序)。然后从该数组中弹出元素?

下面的shuffle函数转载自this answer :

function shuffle(array) {
let 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;
}

const myArr = [1, 2, 3, 4, 5, 6];
shuffle(myArr);
while (myArr.length > 0) {
console.log(myArr.pop());
}

在尝试编写自己的洗牌算法之前请三思……比你或我更聪明的人以前曾在这方面搞砸过。

关于javascript - 从 JS 数组中选择一个值并跳过它,直到显示所有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56927275/

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