【发布时间】:2020-06-17 03:34:08
【问题描述】:
挑战: 例如,当使用 3 个六面骰子时,得到 15 和的概率是多少。例如,这可以通过获得 5-5-5 或 6-6-3 或 3-6-6 或更多选项来实现。
2个骰子的强力解决方案-复杂度为6^2:
假设我们只有 2 个六面骰子,我们可以编写一个非常基本的代码:
public static void main(String[] args) {
System.out.println(whatAreTheOdds(7));
}
public static double whatAreTheOdds(int wantedSum){
if (wantedSum < 2 || wantedSum > 12){
return 0;
}
int wantedFound = 0;
int totalOptions = 36;
for (int i = 1; i <= 6; i++) {
for (int j = 1; j <= 6; j++) {
int sum = i+j;
if (sum == wantedSum){
System.out.println("match: " + i + " " + j );
wantedFound +=1;
}
}
}
System.out.println("combinations count:" + wantedFound);
return (double)wantedFound / totalOptions;
}
7 的输出将是:
匹配:1 6
匹配:2 5
匹配:3 4
匹配:4 3
匹配:5 2
匹配:6 1
组合数:6
0.16666666666666666
问题是如何泛化算法来支持N个骰子:
public static double whatAreTheOdds(int wantedSum, int numberOfDices)
因为我们不能动态创建嵌套的for 循环,所以我们必须采用不同的方法。
我想到了类似的东西:
public static double whatAreTheOdds(int sum, int numberOfDices){
int sum;
for (int i = 0; i < numberOfDices; i++) {
for (int j = 1; j <= 6; j++) {
}
}
}
但未能提出正确的算法。
这里的另一个挑战是 - 有没有一种方法可以有效地做到这一点,而不是 6^N 的复杂性?
【问题讨论】:
-
递归可能是最简单的方法。或者一个计数器,以 6 为基数,有 n 个数字表示 n 个骰子。
-
很确定有一个封闭形式的解决方案?
-
7-7-1怎么来的?一个从 1 到 6 编号的骰子。
-
@ManojBanik 哎呀。修好了。
标签: java algorithm time-complexity probability dice