gpt4 book ai didi

java - 防止冗余随机数

转载 作者:行者123 更新时间:2023-11-29 03:35:20 25 4
gpt4 key购买 nike

我正在尝试根据用户输入的内容以 2 组的形式获取 0 - 499 的随机数。例如234和58,那是一套,但用户可能会提示他们要8套。我试图确保不会出现多余的数字,例如 234 和 58、12 和 444、198 和 58。(58 出现了两次。)

我试图防止这种情况发生的方法是将找到的数字放入数组中,当我检查下一场比赛时,我会检查数组以确保它们尚未被使用。只是想知道最好的方法是什么。很明显,在第一次四处走动时,还没有选择任何数字,所以我不需要检查。但是接下来如果我有多余的人怎么办?我将获取数字,然后检查数组,如果它已经在数组中,我该如何返回并获取新数字?也许做一个循环?

这是我正在做的:

//now add the specified number of random connections
System.out.println();
System.out.println("new connection(s): ");

//array for keeping track of the new connections to prevent redundant add's
int redundant [] = new int[con*2];

for( int i = 1; i <= con; i++ ){
Random ran = new Random();
if( i == 1){
int ran1 = ran.nextInt(sWorld.length-1) + 1;
int ran2 = ran.nextInt(sWorld.length-1) + 1;
redundant[i - 1] = ran1;
redundant[i] = ran2;
System.out.println(" " + ran1 + " - " + ran2);
}
else{
int ran1 = ran.nextInt(sWorld.length-1) + 1;
int ran2 = ran.nextInt(sWorld.length-1) + 1;
//need help
}

提前致谢!

编辑。使用下面的方法(使用集合)

        List<Integer> nums = new LinkedList<Integer>();
for( int i = 0; i <= 499; i++ ){
nums.add(i);
}

//shuffle the collection for more randomness


System.out.println();
System.out.println("new connection(s): ");
for (int x = 1; x <= con; x++){
Collections.shuffle(nums);

Random ran = new Random();
int r1 = nums.remove(ran.nextInt(nums));
int r2 = nums.remove(ran.nextInt(nums));

但是在获取随机数时遇到问题,有什么帮助吗?

最佳答案

只需用所需范围内的所有索引(即 0 到 499)填充一个集合,然后使用 Collections.shuffle() .

关于java - 防止冗余随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15891580/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com