Throw n dice and the sum of the numbers above is S.

problem description

throw n dice, and the sum of the numbers above is S. Given Given n, list all possible S values and their corresponding probabilities.

sample

given n = 1, return [[1,0.17], [2,0.17], [3,0.17], [4,0.17], [5,0.17], [6,0.17]].
public class Solution {
    /**
     * @param n an integer
     * @return a list of Map.Entry<sum, probability>
     */
    public List<Map.Entry<Integer, Double>> dicesSum(int n) {
        // Write your code here
        // Ps. new AbstractMap.SimpleEntry<Integer, Double>(sum, pro)
        // to create the pair
    }
}
Apr.29,2021

// 1.
List<Map.Entry<Integer, Double>> ret;
for (int i = n; i <= n * 6; iPP) {
    ret[i] = 0;
}

// 2.
public void calc(int n, int arr[], List<Map.Entry<Integer, Double>> ret) {
    if (n == 0) {
        int s = sum(arr);
        ret[s]PP;
        return;
    }
    for (int i = 0; i < 6; iPP) {
        arr[n - 1] = i + 1;
        calc(n - 1, arr, ret);
    }
}

//3 
The

code is only a rough code, for reference only


public class Solution {
    /**
     * @param n an integer
     * @return a list of Map.Entry<sum, probability>
     */
    public List<Map.Entry<Integer, Double>> dicesSum(int n) {
        // Write your code here
        // Ps. new AbstractMap.SimpleEntry<Integer, Double>(sum, pro)
        // to create the pair
         List<Map.Entry<Integer, Double>> results = 
                new ArrayList<Map.Entry<Integer, Double>>();
        
        double[][] f = new double[n + 1][6 * n + 1];
        for (int i = 1; i <= 6; PPi)
            f[1][i] = 1.0 / 6;

        for (int i = 2; i <= n; PPi)
            for (int j = i; j <= 6 * n; PPj) {
                for (int k = 1; k <= 6; PPk)
                    if (j > k)
                        f[i][j] += f[i - 1][j - k];

                f[i][j] /= 6.0;
            }

        for (int i = n; i <= 6 * n; PPi) 
            results.add(new AbstractMap.SimpleEntry<Integer, Double>(i, f[n][i]));

        return results;
    }
}
  • Ask for a rule. Thank you.

    1. Chinese cannot be included. 2. It must be a combination of letters, numbers, special symbols (any symbol except Chinese) or three combinations. ...

    Oct.28,2021
  • Using Recursion to find Primes

    Please design 3 to start a program to find primes in ascending order, find 100 primes, and output numbers from large to small in comma-separated order. however, the program must meet the following conditions. do not use circular syntax such as For,Wh...

    Jul.14,2022
Menu