首页 > 解决方案 > 如何在不编写丑陋代码的情况下在具有不同机会的多个选项之间进行选择

问题描述

我在为我的 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 中问过,但在任何编程语言中我都有同样的问题。

我的问题是最优雅的方法是什么

谢谢

标签: javascriptnode.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;
}

推荐阅读