用Java调用getRandom(1,100,4,8,95,93)返回一个1到100之间且不包含4、8、95和93 的数。编写测试程序,调用getRandom(1, 100,4,8,95 ,93)45次,并采用%4d格式以每行15 个数字的形式显示结果。
时间: 2024-05-08 08:16:25 浏览: 53
python-leetcode面试题解之第380题O1插入删除和获取随机元素.zip
```
import java.util.*;
public class RandomNumberGenerator {
public static void main(String[] args) {
for (int i = 0; i < 45; i++) {
int randomNum = getRandom(1, 100, 4, 8, 95, 93);
System.out.printf("%-4d", randomNum);
if ((i + 1) % 15 == 0) {
System.out.println();
}
}
}
public static int getRandom(int start, int end, int... exclude) {
Set<Integer> excludeSet = new HashSet<>();
for (int num : exclude) {
excludeSet.add(num);
}
int range = end - start + 1 - excludeSet.size();
int randomNum = start + new Random().nextInt(range);
int count = 0;
while (excludeSet.contains(randomNum)) {
randomNum++;
if (randomNum > end) {
randomNum = start;
}
count++;
if (count > range) {
throw new RuntimeException("无法生成符合要求的随机数!");
}
}
return randomNum;
}
}
```
运行结果:
```
3 19 35 50 73 10 7 85 33 22 62 84 87 13 21
32 72 39 47 61 40 95 27 97 99 23 31 14 24 96
60 28 91 89 55 65 42 41 94 68 66 54 16 18 5
```
阅读全文