概率算法

最近做了一个活动抽奖需求,项目需要控制预算,概率需要分布均匀,这样才能获得所需要的概率结果。
例如抽奖得到红包奖金,而每个奖金的分布都有一定概率:

红包/(单位元) 概率
0.01-1 40%
1-2 25%
2-3 20%
3-5 10%
5-10 5%

现在的问题就是如何根据概率分配给用户一定数量的红包。

一、一般算法

算法思路:生成一个列表,分成几个区间,例如列表长度100,1-40是0.01-1元的区间,41-65是1-2元的区间等,然后随机从100取出一个数,看落在哪个区间,获得红包区间,最后用随机函数在这个红包区间内获得对应红包数。

//per[] = {40,25,20,10,5}
//moneyStr[] = {0.01-1,1-2,2-3,3-5,5-10}
//获取红包金额
public double getMoney(List<String> moneyStr,List<Integer> per){
        double packet = 0.01;
        //获取概率对应的数组下标
        int key = getProbability(per);
        //获取对应的红包值
        String[] moneys = moneyStr.get(key).split("-");

        if (moneys.length < 2){
            return packet;
        }
        
        double min = Double.valueOf(moneys[0]);//红包最小值
        double max = Double.valueOf(moneys[1]);//红包最大值

        Random random = new Random();
        packet = min + (max - min) * random.nextInt(10) * 0.1;

        return packet;
 }

//获得概率对应的key
public int getProbability(List<Integer> per){
        int key = 0;
        if (per == null || per.size() == 0){
            return key;
        }

        //100中随机生成一个数
        Random random = new Random();
        int num = random.nextInt(100);

        int probability = 0;
        int i = 0;
        for (int p : per){
            probability += p;
            //获取落在该区间的对应key
            if (num < probability){
                key = i;
            }
            
            i++;
        }
        
        return key;

    }
    

时间复杂度:预处理O(MN),随机数生成O(1),空间复杂度O(MN),其中N代表红包种类,M则由最低概率决定。

优缺点:该方法优点是实现简单,构造完成之后生成随机类型的时间复杂度就是O(1),缺点是精度不够高,占用空间大,尤其是在类型很多的时候。

二、离散算法

算法思路:离散算法通过概率分布构造几个点[40, 65, 85, 95,100],构造的数组的值就是前面概率依次累加的概率之和。在生成1~100的随机数,看它落在哪个区间,比如50在[40,65]之间,就是类型2。在查找时,可以采用线性查找,或效率更高的二分查找。

//per[] = {40, 65, 85, 95,100}
//moneyStr[] = {0.01-1,1-2,2-3,3-5,5-10}
//获取红包金额
public double getMoney(List<String> moneyStr,List<Integer> per){
        double packet = 0.01;
        //获取概率对应的数组下标
        int key = getProbability(per);
        //获取对应的红包值
        String[] moneys = moneyStr.get(key).split("-");

        if (moneys.length < 2){
            return packet;
        }
        
        double min = Double.valueOf(moneys[0]);//红包最小值
        double max = Double.valueOf(moneys[1]);//红包最大值

        Random random = new Random();
        packet = min + (max - min) * random.nextInt(10) * 0.1;

        return packet;
 }

//获得概率对应的key
public int getProbability(List<Integer> per){
        int key = -1;
        if (per == null || per.size() == 0){
            return key;
        }

        //100中随机生成一个数
        Random random = new Random();
        int num = random.nextInt(100);

        int i = 0;
        for (int p : per){
            //获取落在该区间的对应key
            if (num < p){
                key = i;
            }
        }
        
        return key;

    }  

算法复杂度:比一般算法减少占用空间,还可以采用二分法找出R,这样,预处理O(N),随机数生成O(logN),空间复杂度O(N)。

优缺点:比一般算法占用空间减少,空间复杂度O(N)。

三、Alias Method

算法思路:Alias Method将每种概率当做一列,该算法最终的结果是要构造拼装出一个每一列合都为1的矩形,若每一列最后都要为1,那么要将所有元素都乘以5(概率类型的数量)。

Alias Method

此时会有概率大于1的和小于1的,接下来就是构造出某种算法用大于1的补足小于1的,使每种概率最后都为1,注意,这里要遵循一个限制:每列至多是两种概率的组合。

最终,我们得到了两个数组,一个是在下面原始的prob数组[0.75,0.25,0.5,0.25,1],另外就是在上面补充的Alias数组,其值代表填充的那一列的序号索引,(如果这一列上不需填充,那么就是NULL),[4,4,0,1,NULL]。当然,最终的结果可能不止一种,你也可能得到其他结果。

prob[] = [0.75,0.25,0.5,0.25,1]
Alias[] = [4,4,0,1,NULL] (记录非原色的下标)
根据Prob和Alias获取其中一个红包区间。
随机产生一列C,再随机产生一个数R,通过与Prob[C]比较,R较大则返回C,反之返回Alias[C]。

//原概率与红包区间
per[] = {0.25,0.2,0.1,0.05,0.4}
moneyStr[] = {1-2,2-3,3-5,5-10,0.01-1}

举例验证下,比如取第二列,让prob[1]的值与一个随机小数f比较,如果f小于prob[1],那么结果就是2-3元,否则就是Alias[1],即4。

我们可以来简单验证一下,比如随机到第二列的概率是0.2,得到第三列下半部分的概率为0.2 * 0.25,记得在第四列还有它的一部分,那里的概率为0.2 * (1-0.25),两者相加最终的结果还是0.2 * 0.25 + 0.2 * (1-0.25) = 0.2,符合原来第二列的概率per[1]。

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

public class AliasMethod {
    /* The random number generator used to sample from the distribution. */
    private final Random random;

    /* The probability and alias tables. */
    private final int[] alias;
    private final double[] probability;

    /**
     * Constructs a new AliasMethod to sample from a discrete distribution and
     * hand back outcomes based on the probability distribution.
     * <p/>
     * Given as input a list of probabilities corresponding to outcomes 0, 1,
     * ..., n - 1, this constructor creates the probability and alias tables
     * needed to efficiently sample from this distribution.
     *
     * @param probabilities The list of probabilities.
     */
    public AliasMethod(List<Double> probabilities) {
        this(probabilities, new Random());
    }

    /**
     * Constructs a new AliasMethod to sample from a discrete distribution and
     * hand back outcomes based on the probability distribution.
     * <p/>
     * Given as input a list of probabilities corresponding to outcomes 0, 1,
     * ..., n - 1, along with the random number generator that should be used
     * as the underlying generator, this constructor creates the probability
     * and alias tables needed to efficiently sample from this distribution.
     *
     * @param probabilities The list of probabilities.
     * @param random        The random number generator
     */
    public AliasMethod(List<Double> probabilities, Random random) {
        /* Begin by doing basic structural checks on the inputs. */
        if (probabilities == null || random == null)
            throw new NullPointerException();
        if (probabilities.size() == 0)
            throw new IllegalArgumentException("Probability vector must be nonempty.");

        /* Allocate space for the probability and alias tables. */
        probability = new double[probabilities.size()];
        alias = new int[probabilities.size()];

        /* Store the underlying generator. */
        this.random = random;

        /* Compute the average probability and cache it for later use. */
        final double average = 1.0 / probabilities.size();

        /* Make a copy of the probabilities list, since we will be making
         * changes to it.
         */
        probabilities = new ArrayList<Double>(probabilities);

        /* Create two stacks to act as worklists as we populate the tables. */
        Stack<Integer> small = new Stack<Integer>();
        Stack<Integer> large = new Stack<Integer>();

        /* Populate the stacks with the input probabilities. */
        for (int i = 0; i < probabilities.size(); ++i) {
            /* If the probability is below the average probability, then we add
             * it to the small list; otherwise we add it to the large list.
             */
            if (probabilities.get(i) >= average)
                large.push(i);
            else
                small.push(i);
        }

        /* As a note: in the mathematical specification of the algorithm, we
         * will always exhaust the small list before the big list.  However,
         * due to floating point inaccuracies, this is not necessarily true.
         * Consequently, this inner loop (which tries to pair small and large
         * elements) will have to check that both lists aren't empty.
         */
        while (!small.isEmpty() && !large.isEmpty()) {
            /* Get the index of the small and the large probabilities. */
            int less = small.pop();
            int more = large.pop();

            /* These probabilities have not yet been scaled up to be such that
             * 1/n is given weight 1.0.  We do this here instead.
             */
            probability[less] = probabilities.get(less) * probabilities.size();
            alias[less] = more;

            /* Decrease the probability of the larger one by the appropriate
             * amount.
             */
            probabilities.set(more,
                    (probabilities.get(more) + probabilities.get(less)) - average);

            /* If the new probability is less than the average, add it into the
             * small list; otherwise add it to the large list.
             */
            if (probabilities.get(more) >= 1.0 / probabilities.size())
                large.add(more);
            else
                small.add(more);
        }

        /* At this point, everything is in one list, which means that the
         * remaining probabilities should all be 1/n.  Based on this, set them
         * appropriately.  Due to numerical issues, we can't be sure which
         * stack will hold the entries, so we empty both.
         */
        while (!small.isEmpty())
            probability[small.pop()] = 1.0;
        while (!large.isEmpty())
            probability[large.pop()] = 1.0;
    }

    /**
     * Samples a value from the underlying distribution.
     *
     * @return A random value sampled from the underlying distribution.
     */
    public int next() {
        /* Generate a fair die roll to determine which column to inspect. */
        int column = random.nextInt(probability.length);

        /* Generate a biased coin toss to determine which option to pick. */
        boolean coinToss = random.nextDouble() < probability[column];

        /* Based on the outcome, return either the column or its alias. */
       /* Log.i("1234","column="+column);
        Log.i("1234","coinToss="+coinToss);
        Log.i("1234","alias[column]="+coinToss);*/
        return coinToss ? column : alias[column];
    }

    public int[] getAlias() {
        return alias;
    }

    public double[] getProbability() {
        return probability;
    }

    public static void main(String[] args) {
        TreeMap<String, Double> map = new TreeMap<String, Double>();

        map.put("1-2", 0.25);
        map.put("2-3", 0.2);
        map.put("3-5", 0.1);
        map.put("5-10", 0.05);
        map.put("0.01-1", 0.4);

        List<Double> list = new ArrayList<Double>(map.values());
        List<String> gifts = new ArrayList<String>(map.keySet());

        AliasMethod method = new AliasMethod(list);
        for (double value : method.getProbability()){
            System.out.println("," + value);
        }

        for (int value : method.getAlias()){
            System.out.println("," + value);
        }

        Map<String, AtomicInteger> resultMap = new HashMap<String, AtomicInteger>();

        for (int i = 0; i < 100000; i++) {
            int index = method.next();
            String key = gifts.get(index);
            if (!resultMap.containsKey(key)) {
                resultMap.put(key, new AtomicInteger());
            }
            resultMap.get(key).incrementAndGet();
        }
        for (String key : resultMap.keySet()) {
            System.out.println(key + "==" + resultMap.get(key));
        }

    }
}

算法复杂度:预处理O(NlogN),随机数生成O(1),空间复杂度O(2N)。

优缺点:这种算法初始化较复杂,但生成随机结果的时间复杂度为O(1),是一种性能非常好的算法。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 213,616评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,020评论 3 387
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 159,078评论 0 349
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,040评论 1 285
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,154评论 6 385
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,265评论 1 292
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,298评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,072评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,491评论 1 306
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,795评论 2 328
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,970评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,654评论 4 337
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,272评论 3 318
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,985评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,223评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,815评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,852评论 2 351

推荐阅读更多精彩内容