4类抽奖算法总结
第一类是常见的有等级的抽奖活动,如一等、二等、三等奖等等
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
// 分别为一、二、三、四等将的奖品数量,最后一个为未中奖的数量。
private static final Integer[] lotteryList = { 5 , 10 , 20 , 40 , 100 };
private int getSum() {
int sum = 0 ;
for ( int v : lotteryList) {
sum += v;
}
return sum;
}
private int getLotteryLevel() {
Random random = new Random(System.nanoTime());
int sum = getSum();
for ( int i = 0 ; i < lotteryList.length; ++i) {
int randNum = Math.abs(random.nextInt()) % sum;
if (randNum <= lotteryList[i]) {
return i;
} else {
sum -= lotteryList[i];
}
}
return - 1 ;
}
|
第二类是不分等级的抽奖活动,仅需要参与人数与奖品总数,各奖品中奖概率相等。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
//另一种抽奖算法,用于公司抽奖,即总参与人数与奖品数固定。
private static final int lotteryNum = 75 ;
private static final int total = 175 ;
private static Set<Integer> lotterySet = new HashSet<Integer>();
static {
for ( int i= 1 ; i <= lotteryNum; ++i) {
lotterySet.add(total*i/lotteryNum);
}
}
private int getLotteryNum2() {
Random rand = new Random(System.nanoTime());
int randNum = Math.abs(rand.nextInt()) % total;
if (lotterySet.contains(randNum)) {
return randNum*lotteryNum/total;
}
return - 1 ;
}
|
第三类 一个商场进行一场抽奖活动,其中有两个奖项,第一个奖项A抽中的概率是1/6,第二个奖项B抽中的概率是5/6;编码实现这个抽奖程序。
思路:
这题考察队随机函数的应用。
由于rand()函数产生的随机数的范围是0-65535,那么将该随机数对6求余,得到的数在0-5之间,且每个数出现概率相等。
[cpp] view plain copy

- #include <iostream>
- #include <cstdio>
- #include <cstdlib>
- #include <ctime>
- #include <algorithm>
- using namespace std;
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。