抽奖活动:随机抽取,份额越大中奖的概率越高,返回中奖用户id(数组的下标为用户id)
public class Come {
// 设数组的长度为100
public static void main(String[] args) {
for (int i = 0; i < 10000; i++) {
int prize = Prize();
if (prize>0&&prize<=100){
System.out.println(prize);
break;
}
}
}
static int[] arr = new int[100];
//生成1000个随机数代表用户的份额
public static int[] course() {
Random random = new Random();
for (int i = 0; i < 100; i++) {
arr[i] = random.nextInt(1000);
}
return arr;
}
public static int Prize() {
int[] arr1 = course();
double sumWeight = 0;//总权重
double randomNumber;//随机数
int random = -1;
//计算总权重
for (int arr2 :
arr1) {
sumWeight += arr2;
}
//产生随机数
randomNumber = Math.random();
try {
//根据随机数在所有奖品的分布的区域确定中奖用户
double d1 = 0;
double d2 = 0;
for (int i = 0; i < arr1.length; i++) {
d2 = arr1[i] / sumWeight;
if (i != 0) {
d1 = arr1[i - 1] / sumWeight;
} else {
d1 = 0;
}
if (randomNumber >= d1 && randomNumber <= d2) {
random = i;
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return random;
}
}