Dices Sum
Throw n dices, the sum of the dices' faces is S. Given n, find the all possible value of S along with its probability.
Example
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 //结果 List<Map.Entry<Integer, Double>> resultList = new ArrayList<>(); if (n < 1) { return resultList; } //二维数组列数 int col = 2; //二维数组行数 int row = 5 * n + 1; long[][] calArr = new long[col][row]; //当前使用行 int curCol = 0; //前一行 int preCol; //开始序号 int startIndex = 0; //结束序号 int endIndex = 5; //半序号 概率具有对称性 int halfIndex = endIndex / 2 + 1; int i, j, k; for (i = 0; i < 6; i++) { //初始化话n=1时 calArr[curCol][i] = 1; } for (i = 1; i < n; i++) { curCol = i % 2; preCol = (curCol + 1) % 2; startIndex = 0; endIndex = 5 * (i + 1); halfIndex = endIndex / 2; for (j = startIndex; j <= halfIndex; j++) { calArr[curCol][j] = 0; //增加一个骰子时 加上新骰子的点数(1/2/3/4/5/6)得到 for (k = 0; k < 6; k++) { if (j - k < 0) { break; } else { calArr[curCol][j] = calArr[curCol][j] + calArr[preCol][j - k]; } } } //对称赋值 for (j = halfIndex + 1; j <= endIndex; j++) { calArr[curCol][j] = calArr[curCol][endIndex - j]; } } long sum = 0; for (i = 0; i < row; i++) { //求和 sum += calArr[curCol][i]; } Map.Entry<Integer, Double> doubleMap; for (i = 0; i < row; i++) { //计算概率 resultList.add(new AbstractMap.SimpleEntry<Integer, Double>(i + n, ((double) calArr[curCol][i] / sum))); } return resultList; }
}