C#&PHP&Java实现Alias Method概率抽奖算法

来源:互联网 发布:淘宝好看的情侣装店铺 编辑:程序博客网 时间:2024/06/05 11:29

最近在做抽奖服务端接口,会涉及到抽奖概率的问题,网上查资料找到一个比较好的抽奖概率的算法,Alias Method概率抽奖算法。今天就来分享一下这个算法的C#、PHP以及Java的实现。

举个例子,游戏中玩家推倒了一个boss,会按如下概率掉落物品:10%掉武器 20%掉饰品 30%掉戒指 40%掉披风。现在要给出下一个掉落的物品类型,或者说一个掉落的随机序列,要求符合上述概率。


一般会想到的两种解法

第一种算法,构造一个容量为100(或其他)的数组,将其中10个元素填充为类型1(武器),20个元素填充为类型2(饰品)...构造完毕之后,在1到100之间取随机数rand,取到的array[rand]对应的值,即为随机到的类型。这种方法优点是实现简单,构造完成之后生成随机类型的时间复杂度就是O(1),缺点是精度不够高,占用空间大,尤其是在类型很多的时候。


第二种就是一般的离散算法,通过概率分布构造几个点,[10, 30, 60, 100],没错,后面的值就是前面依次累加的概率之和(是不是像斐波那契数列)。在生成1~100的随机数,看它落在哪个区间,比如50在[30,60]之间,就是类型3。在查找时,可以采用线性查找,或效率更高的二分查找,时间复杂度O(logN)。

这里推荐一个大牛的两篇文章,从数学入手,探讨各种算法实现。《用JavaScript玩转游戏编程(一)掉宝类型概率》 和《实验比较各离散采样算法》 。想深入了解的朋友推荐看看。

参考他的文章中得到两个概念,PDF(密度分布函数)和 CDF(累积分布函数)两种概率分布,分别对应如上两种算法:

T1234PDF0.10.20.30.4CDF0.10.30.61.0

好了,现在就来说一下Alias Method(别名方法)

在这里我们不深究他的数学原理(http://www.keithschwarz.com/darts-dice-coins/ 这篇文章里详述了其原理),来看看如何使用和实现。譬如说如上的PDF[0.1,0.2,0.3,0.4],将每种概率当做一列,别名算法最终的结果是要构造拼装出一个每一列合都为1的矩形,若每一列最后都要为1,那么要将所有元素都乘以4(概率类型的数量)


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


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

等等,这个问题还没有解决,得到这两个数组之后,随机取其中的一列,比如是第三列,让prob[3]的值与一个随机小数f比较,如果f小于prob[3],那么结果就是3,否则就是Alias[3],即4。

我们可以来简单验证得到的概率是不是正确的,比如随机到第三列的概率是1/4,得到第三列下半部分的概率为1/4*3/5,记得在第一列还有它的一部分,那里的概率为1/4*(1-2/5),两者相加最终的结果还是3/10,符合原来的pdf概率。这种算法初始化较复杂,但生成随机结果的时间复杂度为O(1),是一种性能非常好的算法。

T1234PDF0.10.20.30.4Alias344NULL

一、Alias Method概率抽奖算法的C#实现


  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. namespace Lanhusoft.Core
  8. {
  9. public class AliasMethod
  10. {
  11. /* The probability and alias tables. */
  12. private int[] _alias;
  13. private double[] _probability;
  14. public AliasMethod(List<Double> probabilities)
  15. {
  16. /* Allocate space for the probability and alias tables. */
  17. _probability = new double[probabilities.Count];
  18. _alias = new int[probabilities.Count];
  19. /* Compute the average probability and cache it for later use. */
  20. double average = 1.0 / probabilities.Count;
  21. /* Create two stacks to act as worklists as we populate the tables. */
  22. var small = new Stack<int>();
  23. var large = new Stack<int>();
  24. /* Populate the stacks with the input probabilities. */
  25. for (int i = 0; i < probabilities.Count; ++i)
  26. {
  27. /* If the probability is below the average probability, then we add
  28. * it to the small list; otherwise we add it to the large list.
  29. */
  30. if (probabilities[i] >= average)
  31. large.Push(i);
  32. else
  33. small.Push(i);
  34. }
  35. /* As a note: in the mathematical specification of the algorithm, we
  36. * will always exhaust the small list before the big list. However,
  37. * due to floating point inaccuracies, this is not necessarily true.
  38. * Consequently, this inner loop (which tries to pair small and large
  39. * elements) will have to check that both lists aren't empty.
  40. */
  41. while (small.Count > 0 && large.Count > 0)
  42. {
  43. /* Get the index of the small and the large probabilities. */
  44. int less = small.Pop();
  45. int more = large.Pop();
  46. /* These probabilities have not yet been scaled up to be such that
  47. * 1/n is given weight 1.0. We do this here instead.
  48. */
  49. _probability[less] = probabilities[less] * probabilities.Count;
  50. _alias[less] = more;
  51. /* Decrease the probability of the larger one by the appropriate
  52. * amount.
  53. */
  54. probabilities[more] = (probabilities[more] + probabilities[less] - average);
  55. /* If the new probability is less than the average, add it into the
  56. * small list; otherwise add it to the large list.
  57. */
  58. if (probabilities[more] >= average)
  59. large.Push(more);
  60. else
  61. small.Push(more);
  62. }
  63. /* At this point, everything is in one list, which means that the
  64. * remaining probabilities should all be 1/n. Based on this, set them
  65. * appropriately. Due to numerical issues, we can't be sure which
  66. * stack will hold the entries, so we empty both.
  67. */
  68. while (small.Count > 0)
  69. _probability[small.Pop()] = 1.0;
  70. while (large.Count > 0)
  71. _probability[large.Pop()] = 1.0;
  72. }
  73. /**
  74. * Samples a value from the underlying distribution.
  75. *
  76. * @return A random value sampled from the underlying distribution.
  77. */
  78. public int next()
  79. {
  80. long tick = DateTime.Now.Ticks;
  81. var seed = ((int)(tick & 0xffffffffL) | (int)(tick >> 32));
  82. unchecked
  83. {
  84. seed = (seed + Guid.NewGuid().GetHashCode() + new Random().Next(0, 100));
  85. }
  86. var random = new Random(seed);
  87. int column = random.Next(_probability.Length);
  88. /* Generate a biased coin toss to determine which option to pick. */
  89. bool coinToss = random.NextDouble() < _probability[column];
  90. return coinToss ? column : _alias[column];
  91. }
  92. }
  93. }


二、Alias Method概率抽奖算法的PHP实现


  1. <?php
  2. class AliasMethod
  3. {
  4. private $length;
  5. private $prob_arr;
  6. private $alias;
  7. public function __construct ($pdf)
  8. {
  9. $this->length = 0;
  10. $this->prob_arr = $this->alias = array();
  11. $this->_init($pdf);
  12. }
  13. private function _init($pdf)
  14. {
  15. $this->length = count($pdf);
  16. if($this->length == 0)
  17. die("pdf is empty");
  18. if(array_sum($pdf) != 1.0)
  19. die("pdf sum not equal 1, sum:".array_sum($pdf));
  20. $small = $large = array();
  21. $average=1.0/$this->length;
  22. for ($i=0; $i < $this->length; $i++)
  23. {
  24. $pdf[$i] *= $this->length;
  25. if($pdf[$i] < $average)
  26. $small[] = $i;
  27. else
  28. $large[] = $i;
  29. }
  30. while (count($small) != 0 && count($large) != 0)
  31. {
  32. $s_index = array_shift($small);
  33. $l_index = array_shift($large);
  34. $this->prob_arr[$s_index] = $pdf[$s_index]*$this->length;
  35. $this->alias[$s_index] = $l_index;
  36. $pdf[$l_index] += $pdf[$s_index]-$average;
  37. if($pdf[$l_index] < $average)
  38. $small[] = $l_index;
  39. else
  40. $large[] = $l_index;
  41. }
  42. while(!empty($small))
  43. $this->prob_arr[array_shift($small)] = 1.0;
  44. while (!empty($large))
  45. $this->prob_arr[array_shift($large)] = 1.0;
  46. }
  47. public function next_rand()
  48. {
  49. $column = mt_rand(0, $this->length - 1);
  50. return mt_rand() / mt_getrandmax() < $this->prob_arr[$column] ? $column : $this->alias[$column];
  51. }
  52. }
  53. ?>


三、Alias Method概率抽奖算法的Java实现


  1. package com.lanhusoft.rsaapp;
  2. import android.util.Log;
  3. import java.util.*;
  4. import java.util.concurrent.atomic.AtomicInteger;
  5. public final class AliasMethod {
  6. /* The random number generator used to sample from the distribution. */
  7. private final Random random;
  8. /* The probability and alias tables. */
  9. private final int[] alias;
  10. private final double[] probability;
  11. /**
  12. * Constructs a new AliasMethod to sample from a discrete distribution and
  13. * hand back outcomes based on the probability distribution.
  14. * <p/>
  15. * Given as input a list of probabilities corresponding to outcomes 0, 1,
  16. * ..., n - 1, this constructor creates the probability and alias tables
  17. * needed to efficiently sample from this distribution.
  18. *
  19. * @param probabilities The list of probabilities.
  20. */
  21. public AliasMethod(List<Double> probabilities) {
  22. this(probabilities, new Random());
  23. }
  24. /**
  25. * Constructs a new AliasMethod to sample from a discrete distribution and
  26. * hand back outcomes based on the probability distribution.
  27. * <p/>
  28. * Given as input a list of probabilities corresponding to outcomes 0, 1,
  29. * ..., n - 1, along with the random number generator that should be used
  30. * as the underlying generator, this constructor creates the probability
  31. * and alias tables needed to efficiently sample from this distribution.
  32. *
  33. * @param probabilities The list of probabilities.
  34. * @param random The random number generator
  35. */
  36. public AliasMethod(List<Double> probabilities, Random random) {
  37. /* Begin by doing basic structural checks on the inputs. */
  38. if (probabilities == null || random == null)
  39. throw new NullPointerException();
  40. if (probabilities.size() == 0)
  41. throw new IllegalArgumentException("Probability vector must be nonempty.");
  42. /* Allocate space for the probability and alias tables. */
  43. probability = new double[probabilities.size()];
  44. alias = new int[probabilities.size()];
  45. /* Store the underlying generator. */
  46. this.random = random;
  47. /* Compute the average probability and cache it for later use. */
  48. final double average = 1.0 / probabilities.size();
  49. /* Make a copy of the probabilities list, since we will be making
  50. * changes to it.
  51. */
  52. probabilities = new ArrayList<Double>(probabilities);
  53. /* Create two stacks to act as worklists as we populate the tables. */
  54. Deque<Integer> small = new ArrayDeque<Integer>();
  55. Deque<Integer> large = new ArrayDeque<Integer>();
  56. /* Populate the stacks with the input probabilities. */
  57. for (int i = 0; i < probabilities.size(); ++i) {
  58. /* If the probability is below the average probability, then we add
  59. * it to the small list; otherwise we add it to the large list.
  60. */
  61. if (probabilities.get(i) >= average)
  62. large.add(i);
  63. else
  64. small.add(i);
  65. }
  66. /* As a note: in the mathematical specification of the algorithm, we
  67. * will always exhaust the small list before the big list. However,
  68. * due to floating point inaccuracies, this is not necessarily true.
  69. * Consequently, this inner loop (which tries to pair small and large
  70. * elements) will have to check that both lists aren't empty.
  71. */
  72. while (!small.isEmpty() && !large.isEmpty()) {
  73. /* Get the index of the small and the large probabilities. */
  74. int less = small.removeLast();
  75. int more = large.removeLast();
  76. /* These probabilities have not yet been scaled up to be such that
  77. * 1/n is given weight 1.0. We do this here instead.
  78. */
  79. probability[less] = probabilities.get(less) * probabilities.size();
  80. alias[less] = more;
  81. /* Decrease the probability of the larger one by the appropriate
  82. * amount.
  83. */
  84. probabilities.set(more,
  85. (probabilities.get(more) + probabilities.get(less)) - average);
  86. /* If the new probability is less than the average, add it into the
  87. * small list; otherwise add it to the large list.
  88. */
  89. if (probabilities.get(more) >= 1.0 / probabilities.size())
  90. large.add(more);
  91. else
  92. small.add(more);
  93. }
  94. /* At this point, everything is in one list, which means that the
  95. * remaining probabilities should all be 1/n. Based on this, set them
  96. * appropriately. Due to numerical issues, we can't be sure which
  97. * stack will hold the entries, so we empty both.
  98. */
  99. while (!small.isEmpty())
  100. probability[small.removeLast()] = 1.0;
  101. while (!large.isEmpty())
  102. probability[large.removeLast()] = 1.0;
  103. }
  104. /**
  105. * Samples a value from the underlying distribution.
  106. *
  107. * @return A random value sampled from the underlying distribution.
  108. */
  109. public int next() {
  110. /* Generate a fair die roll to determine which column to inspect. */
  111. int column = random.nextInt(probability.length);
  112. /* Generate a biased coin toss to determine which option to pick. */
  113. boolean coinToss = random.nextDouble() < probability[column];
  114. /* Based on the outcome, return either the column or its alias. */
  115. /* Log.i("1234","column="+column);
  116. Log.i("1234","coinToss="+coinToss);
  117. Log.i("1234","alias[column]="+coinToss);*/
  118. return coinToss ? column : alias[column];
  119. }
  120. public static void main(String[] args) {
  121. TreeMap<String, Double> map = new TreeMap<String, Double>();
  122. map.put("1金币", 0.2);
  123. map.put("2金币", 0.15);
  124. map.put("3金币", 0.1);
  125. map.put("4金币", 0.05);
  126. map.put("未中奖", 0.5);
  127. List<Double> list = new ArrayList<Double>(map.values());
  128. List<String> gifts = new ArrayList<String>(map.keySet());
  129. AliasMethod method = new AliasMethod(list);
  130. Map<String, AtomicInteger> resultMap = new HashMap<String, AtomicInteger>();
  131. for (int i = 0; i < 100000; i++) {
  132. int index = method.next();
  133. String key = gifts.get(index);
  134. if (!resultMap.containsKey(key)) {
  135. resultMap.put(key, new AtomicInteger());
  136. }
  137. resultMap.get(key).incrementAndGet();
  138. }
  139. for (String key : resultMap.keySet()) {
  140. System.out.println(key + "==" + resultMap.get(key));
  141. }
  142. }
  143. }


参考:

http://blog.csdn.net/sky_zhe/article/details/10051967

0 0
原创粉丝点击