x个可能结果的概率 [英] Probability of x possible outcomes

查看:52
本文介绍了x个可能结果的概率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我在编写程序的一部分中,用户可以定义任意数量的随机结果.它们还定义了每个概率(因此,不相等).他们是什么最好的方式来检查发生了什么.注意:我的程序碰巧是Minecraft插件,但问题更多是通用Java插件,因此我试图使代码反映出这一点:

So I am writing a program in part where a user can define as many random outcomes as they want. They also define the probability of each (so no, they are not equal). What is they best way to check which occured. Note: My program happens to be a Minecraft plugin, but the question is more of a general java one, so I am trying to make the code reflect that:

Map<String,Integer> possibilities = new HashMap<String,Integer>();

int x = (int) (Math.random() * 100)

我的想法是创建另一个变量,并在每次添加之前检查的概率,然后检查该概率是否小于x.如果不是冲洗然后重复,但是我不确定如何构造它.

My idea was to create another variable, and add the previous probability checked to it every time, and check if that was less than x. If it wasn't rinse and repeat, but I'm unsure of how to structure this.

例如,如果用户进行配置,那么他有3种不同的结果,分别有30%,20%,50%的机会,我该怎么做?

So for is example: if the user configured it so he has 3 different outcomes, with a 30, 20, 50 percent chance respectively, how would I do this?

推荐答案

使用 NavigableMap ,这将使您可以通过一次简单,干净的查找来检索正确的结果.(并且在内部,这使用了有效的O(log n)查找-并不是您的地图就足够大了,所以很重要.)

Use a NavigableMap, which will allow you to retrieve the correct outcome with one clean and simple lookup. (And internally, this uses an efficient O(log n) lookup—not that your maps will be large enough to matter.)

import java.util.NavigableMap;
import java.util.TreeMap;
import static java.util.concurrent.ThreadLocalRandom.current;

final class LoadedDie {

  public static void main(String... argv) {

    /* One-time setup */
    NavigableMap<Integer, String> loot = new TreeMap<>();
    int cumulative = 0;
    loot.put(cumulative += 20, "Gold");
    loot.put(cumulative += 30, "Iron");
    loot.put(cumulative += 50, "Coal");

    /* Repeated use */
    System.out.println(loot.higherEntry(current().nextInt(cumulative)).getValue());
    System.out.println(loot.higherEntry(current().nextInt(cumulative)).getValue());
  }

}

这篇关于x个可能结果的概率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆