【问题标题】:Calculating dependent consecutive probability using JS for an n amount of times使用 JS 计算相关连续概率 n 次
【发布时间】:2021-12-10 14:28:51
【问题描述】:

我有一个包含 n 种弹珠的数组,这是一个简化的例子:

 let marbles = [
   {variable: “Green marbles”, text: “Green marble”, amount: 10},
   {variable: “Yellow marbles”, text: “Yellow marble”, amount: 12},
   {variable: “Pink marbles”, text: “Pink marble”, amount: 8}
  ]

我希望使用这个数组来计算连续获得绿色、黄色或粉红色大理石而不替换它的概率(这意味着每次绘制大理石时它都是基板)。 举个例子:

in the first pick, the probability of getting a pink marble is: 
8/30.
In the second pick, the probability is now:
7/29 * 8/30
In the third pick, the probability is now: 
6/28 * 7/29 * 8/30

等等。 我已经设法做到这一点,以计算 with 替换的概率,如下所示:

let withReplacementArray = []
let i
let total = marbles.reduce((prev, cur)=> {return prev + cur.amount}, 0)
marbles.forEach((cur)=> {
for(i=1; i<=total; i ++) {
   withReplacementArray.push({
     probability: (Math.pow(cur.amount, i))/(Math.pow(total, i)),
     n: i, 
     text: cur.text
   })
 }
})

简而言之,这种方法不适用于计算没有放回的概率,因为它不再像将其提高到 i 次方那么简单。 有什么建议? 或者有什么公式可以得到这个结果?

【问题讨论】:

    标签: javascript probability


    【解决方案1】:

    从循环内的两个弹珠数量(您感兴趣的类型和总数)中减去一个。为最后一个循环的累积概率保留一个外部变量,而不是幂。

    let marbles = [
       {variable: "Green marbles", text: "Green marble", amount: 10},
       {variable: "Yellow marbles", text: "Yellow marble", amount: 12},
       {variable: "Pink marbles", text: "Pink marble", amount: 8}
    ];
    
    // say we want to pick green
    let greenAmount = marbles[0].amount;
    let total = marbles.reduce((a, { amount }) => a + amount, 0);
    
    let lastProbability = 1;
    while (greenAmount > 0) {
      lastProbability = lastProbability * (greenAmount / total);
      console.log(lastProbability);
      greenAmount--;
      total--;
    }
    // 10/30
    // then 10/30 * 9/29
    // etc

    【讨论】:

    • 你将如何制作它以便为每个大理石提供解决方案?
    • 围绕整个代码循环,而不是硬编码marbles[0].amount;
    • 我试过这样做,但我遇到了循环问题,因为在每种颜色之后总没有被重置
    • 计算循环内的总数,或将其保存在循环外不会重新分配的变量中
    猜你喜欢
    • 1970-01-01
    • 2017-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多