最近做了一个活动抽奖需求,项目需要控制预算,概率需要分布均匀,这样才能获得所需要的概率结果。
例如抽奖得到红包奖金,而每个奖金的分布都有一定概率:
红包/(单位元) | 概率 |
---|---|
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),是一种性能非常好的算法。
网友评论