zoukankan      html  css  js  c++  java
  • 程序员面试题精选100题(43)n个骰子的点数[算法]

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace HellWorld
    {
        class Program
        {
            public static void PrintSumProbabilityOfDices(int num)
            {
                int max = num*6;
                int[,] arr = new int[num + 1,max + 1];
                for (int i = 1; i <= 6;i++ )
                {
                    arr[1, i] = 1;
                }
                for (int k = 2; k <= num;k++ )
                {
                    for (int i = k; i <=6 * k;i++ )
                    {
                        for (int j = 1; j <= 6;j++ )
                        {
                            if(i>=j)
                                arr[k, i] += arr[k-1,i - j];
                        }
                    }
                }
                double total = Math.Pow((double)6, num);
                for (int j = num; j <= max; j++)
                {
                    double ratio = arr[6, j]/total;
                    Console.WriteLine("{0}:{1}",arr[6,j],ratio );
               }
            }
            static void Main(string[] args)
            {
                PrintSumProbabilityOfDices(6);
                Console.ReadLine();
            }
        }
    }
    状态转移方程
    k表示骰子个数,n表示k个骰子的点数和
                    | - F(k-1, n-6) + F(k-1, n-5) + F(k-1, n-4) +   F(k-1, n-3) + F(k-1, n-2) + F(k-1, n-1)  |  对于 k > 0, k <= n <= 6*k 
    F(k, n) = | 
                    |- 0 对于 n < k or n > 6*k
    
    初始化k=1, F(1,1)=F(1,2)=F(1,3)=F(1,4)=F(1,5)=F(1,6)=1
  • 相关阅读:
    [转]Maven类包冲突终极三大解决技巧
    python chardet 模块
    python pretty-errors模块
    认识执行时机
    python对象销毁顺序
    python字符串驻留
    python绘图练习
    小练习2
    小练习
    4G 内存处理 10G 大小的文件
  • 原文地址:https://www.cnblogs.com/waka401/p/2627336.html
Copyright © 2011-2022 走看看