结果
代码
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.ToString;
import java.util.ArrayList;
import java.util.List;
public class LotteryUtils {
public static void main(String[] args) throws InterruptedException {
List<Prize> list = new ArrayList<>();
list.add(new Prize(1L, "一等奖", 5));
list.add(new Prize(2L, "二等奖", 15));
list.add(new Prize(3L, "三等奖", 35));
list.add(new Prize(4L, "谢谢回顾", 45));
Integer t1 = 0;
Integer t2 = 0;
Integer t3 = 0;
Integer t4 = 0;
for (int i = 0; i < 100; i++) {
Prize prize = weightFilter(list);
if(prize.getId() == 1){
t1++;
}else if(prize.getId() == 2){
t2++;
}else if(prize.getId() == 3){
t3++;
}else{
t4++;
}
}
System.out.println("100万次抽结果如下:");
System.out.println("一等奖:"+t1);
System.out.println("二等奖:"+t2);
System.out.println("三等奖:"+t3);
System.out.println("谢谢回顾:"+t4);
}
public static Prize weightFilter(List<Prize> list) {
long weight = list.stream().mapToLong(Prize::getWeight).sum();
int random = (int) Math.floor(Math.random() * weight);
for (int j = 0; j < list.size(); j++) {
if (random - list.get(j).getWeight() < 0) {
return list.get(j);
} else {
random -= list.get(j).getWeight();
}
}
return null;
}
@Data
@ToString
@AllArgsConstructor
public static class Prize {
private Long id;
private String prizeName;
private Integer weight;
}
}