【发布时间】:2015-07-03 11:50:24
【问题描述】:
我目前正在开发一个 java 应用程序,我需要计算滚动各种骰子的每个总和的概率。我支持的骰子类型是 d4(4 面骰子)、d6(6 面骰子)、d8(8 面骰子)、d10、d12 和 d20。用户将能够输入他们想在计算中使用的每种类型的骰子的数量。例如,用户可以输入 6 d6 和 4 d4。
有了这个给定的信息(每种类型的骰子数量),我希望计算每个可能的总和可以滚动的概率。然后,我将使用这些信息创建一个图表,显示所选骰子组合的概率分布。
此应用程序是用 Java 编写的。
我目前所处的位置是我有一个函数,它可以计算仅使用一种大小的骰子的特定总和的概率
/*
Recursively calculates the probability of rolling a particular number
when rolling multiple dice of one type
@param dice Number of dice
@param seekedValue Value whose probability is being calculated
@param sides Number of sides on the type of die
*/
private double diceProb(int dice, int seekedValue, int sides){
if (dice == 0){
if (seekedValue == 0){
return 1.0;
} else {
return 0.0;
}
} else {
double sum = 0;
for (int i = seekedValue - sides; i < seekedValue; i++){
sum += diceProb(dice -1, i, sides) / sides;
}
return sum;
}
}
然后我使用此代码查找所有可能的概率
/*
Variable Explanations:
diceEntries: This array list contains the number of each dice supplied by the user.
It is ordered by number of sides, with d4 at the beginning and d20 at the end
diceValues: This array contains the sides of the dice types
probArray: this array list will contain the probabilities of each sum possible
min: the minimum sum possible
max: the maximum sum possible
*/
ArrayList<Integer> diceEntries
ArrayList<Float> probArray = new ArrayList<>();
int[] diceValues = {4,6,8,10,12,20};
float prob = 0;
for (int i = min; i <= max; i++){
for (int j = 0; j <= 5; j++) {
prob = (float) diceProb(diceEntries.get(j), i, diceValues[j]);
if (prob != 0) {
probArray.add(prob);
}
}
}
我当前的代码只能处理一种尺寸的骰子,即只有 d6s 或 d4s,而不是它们的混合。
如果社区可以提供一些指导,将不胜感激。我也愿意接受过度的方法。例如,我读到生成函数可能是一种更好的方法,但我的组合统计数据有点弱,如果有人确实有办法对其进行编码,很高兴看到它。
非常感谢大家
【问题讨论】:
-
不确定这是否会有所帮助,但此处的示例:link 提供了一种适用于骰子数 (n)、边数 (r) 和目标总和 (k) 的算法
标签: java probability dice