30万个员工,其工卡号码分别是1~30万,抽10万个员工发奖品。有一个随机数生成函数rand()能够生成(0~65535]的整数,请写一个公平的抽奖程序,输出这10万个员工的工卡号码
利用rand5生成rand7算法的原理
import java.util.*;
public class Main {
private static final int NUM_EMPLOYEES = 300000;
private static final int NUM_WINNERS = 100000;
private static final int MAX_RAND = 65535;
public static void main(String[] args) {
Set<Integer> winners = fairLottery();
System.out.println("Number of winners: " + winners.size());
System.out.println("Winners: " + winners);
}
public static Set<Integer> fairLottery() {
Set<Integer> winners = new HashSet<>();
Random random = new Random();
while (winners.size() < NUM_WINNERS) {
int randomNumber = generateEmployeeNumber(random);
winners.add(randomNumber); // 利用 HashSet 自动去重
}
return winners;
}
// 生成 [1, 300000] 范围的随机数
public static int generateEmployeeNumber(Random random) {
while (true) {
int part1 = rand(random); // 生成 [1, 65535]
int part2 = rand(random); // 生成 [1, 65535]
// 合成一个更大的随机数
long largeRand = (long) (part1 - 1) * MAX_RAND + part2;
// 映射到 [1, 300000] 范围
if (largeRand <= (long) NUM_EMPLOYEES * MAX_RAND) {
return (int) ((largeRand - 1) % NUM_EMPLOYEES + 1);
}
}
}
// 模拟 rand() 函数,返回 [1, 65535] 之间的随机整数
public static int rand(Random random) {
return random.nextInt(MAX_RAND) + 1;
}
}
标签:抽奖,int,30,员工,random,winners,static,65535,public
From: https://blog.csdn.net/qq_53199639/article/details/141975155