《剑指offer》第六十题(n个骰子的点数)

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