防止冗余随机数

时间:2013-04-09 00:59:48

标签: java arrays loops random redundancy

我试图根据用户输入的内容,以2组为单位获得随机数0 - 499。例如234和58,那就是一组,但用户可能会提示它们是8组。我试图确保多余的数字不会出现,如234& 58,12& 444,198& 58.(58出现了两次。)

我试图阻止这种情况的方法是将找到的数字放入一个数组中,当我绕过下一个匹配时,我会检查数组以确保它们还没有被使用过。只是想知道这是最好的方式。很明显,在第一次出现时没有选择任何数字,所以我不需要检查。但接下来如果我得到一个多余的话怎么办呢?我将得到数字,然后检查数组,如果它已经在数组中,我如何回去获取新数字?一个while循环可能吗?

这就是我在做什么:

//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
        }

提前感谢!

修改。使用下面的maethod(使用集合)

        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));

但无法获取随机数,有什么帮助?

3 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

一种方法是创建一个0-499的数字列表

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

然后随机播放列表

Collections.shuffle(nums);

然后,每当您需要0-499之间的非重复随机数时,只需从列表中删除一个元素

int x = nums.remove()

答案 2 :(得分:0)

使用while周期并使用array。虽然您的索引不在范围之外,但会生成两个数字。如果它们不是冗余的,则将它们添加到数组中并相应地增加索引。如果它们是多余的,什么也不做,那么while周期的下一次迭代将产生两个新的数字。