今天学习算法的时候碰见一个骰子点数分布概率的问题:
Dice simulation.
The following code computes the exact probability distribu-tion for the sum of two dice:
int SIDES = 6;
double[] dist = new double[2*SIDES+1];
for (int i = 1; i <= SIDES; i++)
for (int j = 1; j <= SIDES; j++)
dist[i+j] += 1.0;
for (int k = 2; k <= 2*SIDES; k++)
dist[k] /= 36.0;
The value dist[i] is the probability that the dice sum to k. Run experiments to vali-date this calculation simulating N dice throws, keeping track of the frequencies of oc-currence of each value when you compute the sum of two random integers between 1and 6. How large does N have to be before your empirical results match the exact resultsto three decimal places?
其实这道题要做出来的关键就是求出投了n个骰子之后所有点数和出现的分布:
先贴代码:
/**
* run experiments to validate this calculation simulating N dice throws,
* keeping track of the frequencies of occurrence of each value when you compute the sum of two random integers between 1 and 6.
* How large does N have to be before your empirical results match the exact results to three decimal places?
* @author xiehang
*/
public class Ex1_1_35 {
public static void main(String[] args) {
int side = 6;
final int n = 3; //number of dice
double total = Math.pow(6, n);
int[] a1 = new int [6*n+1]; // a1 is for calculate
int[] a2 = new int [6*n+1]; // a2 is for store the result
int result = 0;
//for the first dice
for(int i= 1; i <=side; i++ ){
a1[i]++;
}
a2 = Util.arrayCopy(a1);
System.out.println("When we have 1 dice");
Util.printArray(a1);
//for the dice after 1
for(int i = 2; i <= n; i++ ){
// each dice will scan from number 1 to the biggest number
for(int k = 0; k < 6 * i +1; k++){
/**
* 原理:
* 先定义第一个骰子的所有可能: 1-6各出现一次
* 再接下去的骰子进入循环:
* 已知下一次点数k出现的和等于上一次的点数为k-1,k-2,k-3,k-4.k-5.k-6出现的和
* e.g. 点数7出现的是点数1,2,3,4,5,6出现的和
* 以这个原理循环下去
*/
for(int j = 1; j <= 6;j++){
if(k-j >=0){ // k-j 相当于上面出现的k-1,k-2
result += a2[k-j];
}
/**
* 解释为何要用a1,a2两个array操作:
* 如果只用一个a1操作的话,
* 前面的数变了之后会影响之后的数
* 所以要用两个array操作
*
* 为何不能用a1[k] += a2[k-j]:
* a1[k] 之前是有一个值的
* 所以在加上去也会让结果不正确
* 所以引入一个新的数储存了以后再变0不断转存就可以了
*/
}
a1[k] = result;
result = 0;
}
a2 = Util.arrayCopy(a1);
System.out.println("When we have " + i + " dice: ");
Util.printArray(a2);
}
System.out.println("End");
Util.printArray(a2);
System.out.println("Here is the rate: ");
for(int i = 1; i < 6*n+1; i++ ){
System.out.println("The rate for number "+ i +" appears is: " + String.format("%.2f", a2[i]/total*100) + "%");
}
}
}