在java中生成一个随机点数组,没有重复项

时间:2012-04-16 21:45:03

标签: java random

我对Java很新,我想生成一个长度为'number'的随机(x,y)坐标数组,其中不包含重复项。可以重复x或y值,但必须没有重复的(x,y)坐标。输出不必是点,只是某种方式保持坐标的x,y值。

我可以生成一个随机点数组,并尝试使用Set来确保没有重复值,但遇到了问题。我尝试使用条件“while(set.size)”和应该禁止重复的'add'方法,以创建包含唯一点的正确大小的输出。

这是代码:

Set<Point> set = new HashSet<Point>();
Random position = new Random();
Point test=new Point();

do{
    test.x=position.nextInt(xx);
    test.y=position.nextInt(yy);   
    //xx and yy are the random number limits called from another part of the code
    set.add(test);     
}
while (set.size()<number);

List<Object> list = new ArrayList<Object>(set);
Object[] coord = list.toArray();

这会输出一个正确长度的数组,但每个元素都是相同的。任何人都可以提供任何帮助吗?

由于

3 个答案:

答案 0 :(得分:5)

每次循环时,

测试指向空间中的相同变量,以修复在循环内创建新实例 - 而不仅仅是在它之前的一次:

Set<Point> set = new HashSet<Point>();
Random position = new Random();
Point test;

do{
    test = new Point();
    test.x=position.nextInt(xx);
    test.y=position.nextInt(yy);   
    //xx and yy are the random number limits called from another part of the code
    set.add(test);     
}
while (set.size()<number);

List<Object> list = new ArrayList<Object>(set);
Object[] coord = list.toArray();

答案 1 :(得分:2)

您正在修改相同的点对象。但是,由于您每次都更改X和Y,因此您还更改了哈希码和点的相等性,因此您最终会在集合中多次放置相同的对象。有趣的案例。

尝试

do{
   test = new Point();
   test.x=position.nextInt(xx);
   test.y=position.nextInt(yy);   
   //xx and yy are the random number limits called from another part of the code
   set.add(test);     
}
while (set.size()<number);

答案 2 :(得分:0)

值随机选择,但不能重复

    Random rndm = new Random();
    String[] selectedNumber = new String[15];
    String[] sequanceNumber = {"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15"};

    //*****FIRST LOOP START*****//
    for(byte a = 0; a < 15;){

        int temp = rndm.nextInt(15)+1;

        //*****SECOND LOOP START*****//
        for(byte b = 0; b < 15; b++){

            String s4 = temp+"";

            //*****CHECKING CONDITION START*****//
            if(s4.equals(sequanceNumber[b]) ){


                selectedNumber[a] = s4;

                String s1 = sequanceNumber[b];
                s1 = s1.replace(s1, " ");
                sequanceNumber[b] = s1;

                a++;

            }
            //*****CHECKING CONDITION END*****//
        }
        //*****SECOND LOOP END*****//
    }
    //*****FIRST LOOP END*****//


    //*****PRINT ALL RANDOM VALUES BUT NOT REPEATED VALUES*****//
    System.out.println(Arrays.toString(selectedNumber));