Title: Put n Dice still on the ground. The sum of the points on the upper side of the dice is S, enter N, and print out the probability that all possible values of s are present.
Solution One: Based on recursive calculation of the dice points, time efficiency is not high enough
Now we consider how to count the number of occurrences of each point.
To find out the number of N dice and. be able to divide n dice into two piles first: the first pile has only one. There's another one with n-1. The single one has the potential to show points from 1 to 6.
We need to calculate each point from 1 to 6 and the remaining n-1 dice to calculate the number of points and.
Then the rest of the n-1 dice are divided into two piles, the first pile only one. The second pile has a n-2.
We add the points of the last single dice and the points of the individual dice. And n-2 a dice to calculate the points and. Analysis here, we are not difficult to find that this is a kind of recursive thinking. The condition of the end of recursion is that there is only one die left.
Solution Two: Based on the cycle of the dice to find the number of points, good time performance
To solve the problem in a different way, we can consider using two arrays to store the number of occurrences of each review of the dice points. In a single loop. The nth number in each array represents the number of times the dice and N appear.
In the next round of loops, we add a new dice, and the number of occurrences of n at this time. In the next round, we add a new dice, at this time and the dice for n should be equal to the number of dice in the last cycle and the sum of the number of n-1,n-2,n-3,n-4,n-5, so we have an array of the nth number of the previous array is set to the corresponding section n-1. N-2. N-3,n-4,n-5
The implementation of code based on this idea is as follows:
/** * N Dice points */package swordforoffer;/** * @author Jinshuangqi * * August 11, 2015 */public class E43dicsprobability { /* * Put n dice still on the ground, all dice to the upper side of the sum of points for S, enter N, print out the probability of all possible s */public void printprobability (int number) {if (number < 1) return; int g_maxvalue = 6;int[][] probabilities = new int[2][];p robabilities[0] = new Int[g_maxvalue * number + 1];p robabilities[ 1] = new Int[g_maxvalue * number + 1];int flag = 0;for (int i = 1; I <= g_maxvalue; i++) Probabilities[0][i] = 1;for (in t k = 2; K <= number; ++k) {for (int i = 0; i < K; ++i) Probabilities[1-flag][i] = 0;for (int i = k; I <= g_maxvalue * k; ++i) {Probabili Ties[1-flag][i] = 0;for (int j = 1; J <= I && J <= g_maxvalue; ++j) probabilities[1-flag][i] + = Probabili TIES[FLAG][I-J];} flag = 1-flag;} Double total = Math.pow (g_maxvalue, number); for (int i = number; I <= g_maxvalue * number; i++) {double ratio = (double ) Probabilities[flag][i]/total; System.out.println (i); System.out.println (ratio);}}}
Sword Point (Java Edition): N Dice points