最近需要写一个抽奖的功能(附带权重),根据这位博主https://blog.51cto.com/u_16213431/7116970,的算法理解了一下,记录下来
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class HelloWorld {
public static void main(String []args) {
List<String> participants = new ArrayList<>();//建立一个参与者数组(也可以是参与抽奖的物品数组)
participants.add("Alice");
participants.add("Bob");
participants.add("Charlie");
participants.add("David");
List<Integer> weights = new ArrayList<>();//建立一个权重数组
weights.add(1);
weights.add(2);
weights.add(3);
weights.add(4);
int totalWeight = weights.stream().mapToInt(Integer::intValue).sum();//计算权重总量,就是把权重数组中的权重加起来
Random random = new Random();
int randomNumber = random.nextInt(totalWeight);//产生 (0 ~ 总权重)中的随机数
int cumulativeWeight = 0;
int index = 0;
for (int weight : weights) {//循环权重数组,并计算累积权重
cumulativeWeight += weight;//计算累积权重
if (randomNumber < cumulativeWeight) { //如果上面生成的随机数落在在个权重区间内,则跳出循环,使用当前的这个 参与者数组 下标,否则就进入下一个权重区间进行判断
break;
}
index++;
}
String winner = participants.get(index);
System.out.println("The winner is: " + winner);
}
}
标签:抽奖,java,权重,int,add,算法,weights,participants From: https://www.cnblogs.com/luzanzan/p/17877530.html