javascript - 我可以制作一个从列表中生成三个不重复短语的机器人吗?
问题描述
我一直在尝试自学 Discord 机器人,但我是菜鸟,所以请多多包涵。首先我想说的是,我确实通过这个网站找到了这个,但我想出的一切似乎只适用于数字,而不是文字......
我正在尝试让机器人从列表中给出三个响应,而没有任何重复的机会。我了解通过防止项目重复,生成的响应不再是“随机的”。这是我现在想出的解决方法:
client.on('message', message => {
const list1 = [
'example A', 'example B'
]
const list2 = [
'example C', 'example D'
]
const list3 = [
'example E', 'example F'
]
if (message.content.startsWith(`${prefix}fmk`)) {
message.channel.send(`**redacted, Marry, Kill:**\n\n${list1[Math.floor(Math.random() * list1.length)]}\n${list2[Math.floor(Math.random() * list2.length)]}\n${list3[Math.floor(Math.random() * list3.length)]}`);
}
});
显然你可以看到这个问题。它阻止了类似的响应,example A, example A, example A,
但也使得不可能获得类似的组合example A, example B, example C
。
有没有一种方法可以让我拥有一个从示例 A 到示例 F 的列表,并且仍然从中获得三个不重复的结果?
我希望这是有道理的。谢谢 :)
解决方案
You could use a Fisher-Yates Shuffle
to move 3 values around randomly:
function shuffle(array) {
var i = array.length,
j = 0,
temp;
while (i--) {
j = Math.floor(Math.random() * (i+1));
// swap randomly chosen element with current element
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
var ranStrings = shuffle(["Example A", "Example B", "Example C"]); //calling the func
Note: this function not only shuffles the array, but only allowed unique values to be output
EDIT: As mentioned above, this isn't really a Discord.js question, although it is related to a bot, it is more asking about Javascript
, and it would be more suited there.
推荐阅读
- windows - 是否可以进行 Windows 系统调用来查看进程当前正在使用的操作系统线程数?
- android - android 应用程序在启动时崩溃(致命异常,没有为 ID 0xffffffff 找到包 ID ff)
- nginx - 在 docker 文件中添加 Nginx 的健康检查
- node.js - 使用 Formik 会导致我的网络应用出现问题
- sql - 从 impala select 获取多个列值并将其存储在 shell 脚本中的单独变量中
- json - 在 Kotlin 中从类似 JSON 的字符串中解析列表
- django - 在 Django 项目中意外删除了数据库表。如何重新进行迁移?
- c - 为什么 rand() %max+min 公式在(1000 到 1112)之间没有给出所需的输出?
- java - 问题 Cors:请求的资源上不存在“Access-Control-Allow-Origin”标头
- .net-core - 如何从 Identity 表中获取数据 - AspNetUsers?