我目前正在开发一个Java应用程序,需要计算各种骰子的每个点数出现的概率。我支持的骰子类型有d4(四面体骰子)、d6(六面体骰子)、d8(八面体骰子)、d10、d12和d20。用户可以输入他们想要在计算中使用的每种骰子的数量。例如,用户可能输入6个d6和4个d4。
根据这些信息(每种骰子的数量),我将计算每个可能点数被投出的概率。然后,我将使用这些信息创建一个图表,显示所选骰子组合的概率分布。
该应用程序是用Java编写的。
目前我已经编写了一个函数,用于仅使用一种骰子计算特定点数的概率。
我使用这段代码来查找所有可能的概率。
根据这些信息(每种骰子的数量),我将计算每个可能点数被投出的概率。然后,我将使用这些信息创建一个图表,显示所选骰子组合的概率分布。
该应用程序是用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);
}
}
}
我的当前代码只能处理一种大小的骰子,即只有d6或d4而不能混合使用。
如果社区能提供一些指导,那将不胜感激。我也可以接受其他方法。例如,我已经了解到生成函数可能是更好的方法,但我的组合统计学有点薄弱,如果有人能编写出这样的代码,那就太好了。
非常感谢大家。