来自枚举的随机值的概率
我有一个枚举,我想从中随机选择一个值,但不是真正随机的。我希望到目前为止,某些值不太可能被选择。这是我到目前为止所得到的......
private enum Type{
TYPE_A, TYPE_B, TYPE_C, TYPE_D, TYPE_E;
private static final List<Type> VALUES =
Collections.unmodifiableList(Arrays.asList(values()));
private static final int SIZE = VALUES.size();
private static final Random RANDOM = new Random();
public static Type randomType() {
return VALUES.get(RANDOM.nextInt(SIZE));
}
}
是否有一种有效的方法为每个值分配概率?
从此处找到的代码
I have an enum that I would like to randomly select a value from, but not truly random. I would like some of the values to be less likely of being selected so far. Here is what I have so far...
private enum Type{
TYPE_A, TYPE_B, TYPE_C, TYPE_D, TYPE_E;
private static final List<Type> VALUES =
Collections.unmodifiableList(Arrays.asList(values()));
private static final int SIZE = VALUES.size();
private static final Random RANDOM = new Random();
public static Type randomType() {
return VALUES.get(RANDOM.nextInt(SIZE));
}
}
Is there an efficient way of assigning probabilities to each of these values?
Code found from here
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
有几种方法可以做到这一点,其中一种与您的方法类似
several ways to do it, one of them, similar to your approach
这是随机选择
枚举
值的通用方法。您可以按照此处的建议调整概率。Here's a generic approach to choosing an
enum
value at random. You can adjust the probabilities as suggested here.假设您有有限数量的值,您可以为每个值拥有一个单独的权重数组(float[] 权重;)。这些值介于 0 和 1 之间。当您选择随机值时,还会生成另一个随机数,并且仅当第二个生成的数字低于该值的权重时才选择该值。
Assuming you have a finite number of values you could have a separate array (float[] weights;) of weights for each value. These values would be between 0 and 1. When you select a random value also generate another random number between and only select the value if the second generated number is below the weight for that value.
您可以通过提供自定义构造函数来创建具有关联数据 b 的枚举,并使用该构造函数为概率分配权重,然后
You can create an enum with associated data bby provding a custom constructor, and use the constructor to assign weightings for the probabilities and then
这是另一种选择,它允许在运行时指定分发。
包括 Alexey Sviridov 的建议。当有很多选择时,random() 方法也可以结合 Ted Dunning 的建议。
Here is another alternative which allows the distribution to be specified at runtime.
Includes suggestion from Alexey Sviridov. Also method random() could incorporate suggestion from Ted Dunning when there are many options.
您可以使用 EnumeratedDistribution 来自 Apache Commons Math 库。
You can use EnumeratedDistribution from the Apache Commons Math library.