javascript - 如何在不编写丑陋代码的情况下在具有不同机会的多个选项之间进行选择
问题描述
我在为我的 JS 代码问这个问题,但这实际上是我在每种编程语言中都遇到的问题。
假设我在模拟中有 5 个狗的名字,我可以将它们保存在一个数组中,并为每条狗选择一个随机的名字,就像这样
var NAMES = ["Scafy","Shimshon","WoofWoof","Mitzy","AnotherDogName"]//possible names for the dogs
dog.name = NAMES[Math.floor(Math.random()*NAMES.length)] // chooses a random name from for the dog
所以这很简单。但我的问题是,当我希望某些相同的机会更高或更低时,使用 5 个名称并不难做到这一点:
通过做这个丑陋的烂摊子,给 WoofWoof 比其他名字更高的被选中的机会:
var NAMES = ["Scafy","Shimshon","WoofWoof","Mitzy","AnotherDogName"]//possible names for the dogs
function choose(){
var random = Math.random()*100
var name = NAMES[0]
if (random>20)
name = NAMES[1]
if (random>30)
name = NAMES[2]
if (random>80)
name = NAMES[3]
if (random>90)
name = NAMES[4]
return name
}
这种方法有效,但它很丑陋,并且当有很多选项可供选择并且有很多不同的机会时,它会变得难以置信地复杂。
我确信我不是唯一遇到这个问题的人,而且我觉得我错过了一个非常优雅的解决方案,它隐藏在我的鼻子下方(我希望这句话在英语中也有意义)
这是一个普遍的问题,我在 JS 中问过,但在任何编程语言中我都有同样的问题。
我的问题是最优雅的方法是什么
谢谢
解决方案
您希望使您的代码看起来更好并且更具可扩展性吗?如果是这样,这个答案会帮助你。
//dog names and chances
var NAMES = [
{
name: "Scafy",
chance: 0.2
},
{
name: "Shimshon",
chance: 0.1
},
{
name: "WoofWoof",
chance: 0.5
},
{
name: "Mitzy",
chance: 0.1
},
{
name: "AnotherDogName",
chance: 0.1
}
]
//In chances dont add up to 1
var maxChance = 0;
for (let i = 0; i < NAMES.length; i++) {
maxChance += NAMES[i].chance;
}
function choose() {
//to make chance range fair.
var random = Math.random() * maxChance
var name;
//keeps track of were one is in the chancing
let randomTrack = 0;
//chancing
for (let i = 0; i < NAMES.length; i++) {
randomTrack += NAMES[i].chance;
if (random <= randomTrack) {
name = NAMES[i].name;
//stop when you dog got lucky
break;
}
}
return name;
}
推荐阅读
- python - Twitter Data:有没有办法根据条件进行拆分?
- python - 使用 numpy append 和 hstack 追加列和行的问题
- java - java数组中文件的访问路径
- python - 将函数变成没有参数的生成器函数
- python - 如何将控制台脚本/入口点添加到调用类函数 python 的 setup.py
- python - views.py 中的 Django TypeError/(预期的 str、bytes 或 os.PathLike 对象,不是列表)
- javascript - 将 Vuex 与 Vue.set 与一个也是可观察对象的对象进行变异是否是一种好习惯
- loops - Racket 中的 While 循环
- kubernetes-helm - 如何修复通过 helm-rook 安装的 Operator pod 的 dial tcp 10.96.0.1:443: i/o timeout 错误?
- angular - Angular 8 菜单中的用户登录/注销按钮未更新