java - 防止冗余随机数

标签 java arrays loops random redundancy

我正在尝试根据用户输入的内容以 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/

相关文章:

php - 如何跳过数组循环中的第一个键?

java - 有没有办法在 for 循环中链接列表(或 map )?

java - 如何在 Java 中对接口(interface)对象使用 try-with-resources 语句

java - double 值足够大会在 Java 中返回错误

java-将图像旋转到其位置

php - Jquery - 根据数组结果更改输入背景 css

java - 如何每 X 分钟清除一次应用程序缓存?

javascript - 不注意数组长度条件的无限循环

bash - 为什么 'for' 循环比从文件读取的 'while' 循环更快?

java - 需要在类中实现do、while循环