// 面试题60:n个骰子的点数 // 题目:把n个骰子扔在地上,所有骰子朝上一面的点数之和为s。输入n,打印出s // 的所有可能的值出现的概率。 #include <iostream> #include <math.h> int g_maxValue = 6; // ====================方法一==================== //使用递归,还是会有重复计算 void Probability(int number, int* pProbabilities); void Probability(int original, int current, int sum, int* pProbabilities); void PrintProbability_Solution1(int number) { if (number < 1) return; int maxSum = number * g_maxValue; int* pProbabilities = new int[maxSum - number + 1];//建立一个长为maxSum - number + 1的数组,用来统计次数 for (int i = number; i <= maxSum; ++i)//初始化为0 pProbabilities[i - number] = 0; Probability(number, pProbabilities);//统计次数 int total = pow((double)g_maxValue, number); for (int i = number; i <= maxSum; ++i) { double ratio = (double)pProbabilities[i - number] / total; printf("%d: %e ", i, ratio); } delete[] pProbabilities; } void Probability(int number, int* pProbabilities) { for (int i = 1; i <= g_maxValue; ++i) Probability(number, number, i, pProbabilities); } //划分为1个和n-1个两堆色子,然后迭代如此划分,遍历所有可能,然后pProbabilities数组相应加1 void Probability(int original, int current, int sum, int* pProbabilities) { if (current == 1) { pProbabilities[sum - original]++; } else { for (int i = 1; i <= g_maxValue; ++i) { Probability(original, current - 1, i + sum, pProbabilities); } } } // ====================方法二==================== //使用循环方法,需要找到统计新的一个色子的规律 void PrintProbability_Solution2(int number) { if (number < 1) return; int* pProbabilities[2]; pProbabilities[0] = new int[g_maxValue * number + 1]; pProbabilities[1] = new int[g_maxValue * number + 1]; for (int i = 0; i < g_maxValue * number + 1; ++i)//建立两个数组,初始化为0 { pProbabilities[0][i] = 0; pProbabilities[1][i] = 0; } int flag = 0; for (int i = 1; i <= g_maxValue; ++i) pProbabilities[flag][i] = 1;//第一个色子,每个值出现次数为1,值1~g_maxValue for (int k = 2; k <= number; ++k)//从第二个色子开始统计 { for (int i = 0; i < k; ++i) pProbabilities[1 - flag][i] = 0;//把另一个数组的k之前的次数清零,因为那是以前的统计结果,后面不可能出现的值 for (int i = k; i <= g_maxValue * k; ++i)//对于另一个数组而言,统计一个新的色子,其每个和的次数等于当前数组的前六个值的和 { pProbabilities[1 - flag][i] = 0; for (int j = 1; j <= i && j <= g_maxValue; ++j) pProbabilities[1 - flag][i] += pProbabilities[flag][i - j]; } flag = 1 - flag; } double total = pow((double)g_maxValue, number); for (int i = number; i <= g_maxValue * number; ++i) { double ratio = (double)pProbabilities[flag][i] / total; printf("%d: %e ", i, ratio); } delete[] pProbabilities[0]; delete[] pProbabilities[1]; } // ====================测试代码==================== void Test(int n) { printf("Test for %d begins: ", n); printf("Test for solution1 "); PrintProbability_Solution1(n); printf("Test for solution2 "); PrintProbability_Solution2(n); printf(" "); } int main(int argc, char* argv[]) { Test(1); Test(2); Test(3); Test(4); Test(11); Test(0); system("pause"); return 0; }