zoukankan      html  css  js  c++  java
  • 已知多个奖品概率,取奖品

    两种方法: 

    1、 定义一个最大区间,如100000,新建一个区间数组,如a[10,110,1110,100000],然后出0~100000的随机数,在哪个区间就是哪个。 注意:区间的差值/最大上限=目标概率    (要判断是哪个区间,只要for循环一下取第一个 a[i]<[随机数i+1 即可)

    2、 定义一个大数组,如a[100000],按照概率往里填充目标值,如a[1,1,1, …… 2,2,…… ,5,……],然后打乱(随你怎么打乱都行),再出0~99999的随机数n,取a[n]即可。 注意:所有概率和必须等于1,不要漏掉你不必控制出现 未中奖” 的概率。

     

    第一种方式实现:

            public static int getRandomNum(int[] arr, int[] probablility)
            {
                if (arr.Length!=probablility.Length)
                {
                    return -1;
                }
                Random ran =new Random();
                int ran_num = ran.Next(10000);
                int temp = 0;
                for (int i = 0; i < arr.Length; i++)
                {
                    temp += probablility[i];
                    if (ran_num<temp)
                    {
                        return arr[i];
                    }
                }
                return -1;
            }

     

                for (int i = 0; i < 100000; i++)
                {
                    Console.Write(getRandomNum(new int[] { 0, 1, 2, 3, 4, 5 }, new int[] { 7878, 1000, 100, 20, 1000, 2 }));
                }

  • 相关阅读:
    [Install] TeamViewer
    [2017
    [2017 ACL] 对话系统
    [2018 ACL Short and System] 对话系统
    Git分支创建与合并
    Git常用命令
    JSONObject转换分析
    数据库行锁实现
    Jenkins安装
    Tomcat热部署,Web工程中线程没有终止
  • 原文地址:https://www.cnblogs.com/ZhengGuoQing/p/2890270.html
Copyright © 2011-2022 走看看