Dices Sum解题

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;
}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值