这道题其实也不难,递归的想法很简单:
把目前n个骰子分成两堆:1堆1个(可以枚举点数1-6),1堆有n-1个。递推到最后,n=0时,累计起来的点数的次数就+1啦
之所以写这篇博客,是因为我觉得书中的递归代码写得有点混乱(并没有贬低作者的意思),所以贴一下我自己认为比较好的写法:
递归解法
#include <cstdio>
#include <vector>
#include <cmath>
using namespace std;
typedef unsigned int uInt;
const int low = 1, high = 6;
void prob(vector<int>& count, uInt n, int currentSum) {
if (n == 0) {
++count[currentSum];
return;
}
--n;
for (int i = low; i <= high; ++i) {
prob(count, n, currentSum+i);
}
}
void cal(uInt n) {
vector<int> count(high*n+1);
prob(count, n, 0);
int totalCount = pow(6, n), sum = 0;
for (uInt i = n; i < count.size(); ++i) {
sum += count[i];
printf("点数为%d的概率为%.3lf, count=%d\n",
i, count[i]*1.0/totalCount, count[i]);
}
printf("sum=%d, totalCount=%d\n\n", sum, totalCount);
}
int main() {
cal(1);
cal(2);
cal(3);
return 0;
}
输出结果为(其中有挺多调试信息的):
点数为1的概率为0.167, count=1
点数为2的概率为0.167, count=1
点数为3的概率为0.167, count=1
点数为4的概率为0.167, count=1
点数为5的概率为0.167, count=1
点数为6的概率为0.167, count=1
sum=6, totalCount=6
点数为2的概率为0.028, count=1
点数为3的概率为0.056, count=2
点数为4的概率为0.083, count=3
点数为5的概率为0.111, count=4
点数为6的概率为0.139, count=5
点数为7的概率为0.167, count=6
点数为8的概率为0.139, count=5
点数为9的概率为0.111, count=4
点数为10的概率为0.083, count=3
点数为11的概率为0.056, count=2
点数为12的概率为0.028, count=1
sum=36, totalCount=36
点数为3的概率为0.005, count=1
点数为4的概率为0.014, count=3
点数为5的概率为0.028, count=6
点数为6的概率为0.046, count=10
点数为7的概率为0.069, count=15
点数为8的概率为0.097, count=21
点数为9的概率为0.116, count=25
点数为10的概率为0.125, count=27
点数为11的概率为0.125, count=27
点数为12的概率为0.116, count=25
点数为13的概率为0.097, count=21
点数为14的概率为0.069, count=15
点数为15的概率为0.046, count=10
点数为16的概率为0.028, count=6
点数为17的概率为0.014, count=3
点数为18的概率为0.005, count=1
sum=216, totalCount=216
迭代解法
如果理解了上面的递归解法,其实转成迭代也很简单!
假设我们知道了前n-1个骰子构成的点数的情况,比如点数为2有1中情况,点数为3有3种情况……,那么就可以很轻松推断出前n个骰子构成的点数的情况了!就是分别给前面的每个点数加上1,2,3,4,5,6,构成新的点数的情况数。
原书用了两个数组,我用了两个map,空间的重用性不够好,不过可读性增加了一点:
#include <cstdio>
#include <vector>
#include <cmath>
#include <map>
using namespace std;
void cal(int n) {
if (n <= 0)
return;
static const int low = 1, high = 6;
map<int, int> count;
count[0] = 1;
for (int i = 1; i <= n; ++i) {
map<int, int> now;
map<int, int>::iterator it = count.begin();
while (it != count.end()) {
int number = it->first, cnt = it->second;
for (int j = low; j <= high; ++j) {
now[number + j] += cnt;
}
++it;
}
count = now;
}
int totalCount = pow(6, n), sum = 0;
map<int, int>::iterator it = count.begin();
while (it != count.end()) {
sum += it->second;
printf("点数为%d的概率为%.3lf, count=%d\n",
it->first, it->second*1.0/totalCount, it->second);
++it;
}
printf("sum=%d, totalCount=%d\n\n", sum, totalCount);
}
int main() {
cal(1);
cal(2);
cal(3);
return 0;
}