提问者:小点点

在java中生成无重复的随机点数组


我对Java相当陌生,我想生成一个长度为“数字”的随机(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个答案

匿名用户

test每次循环时都指向空间中的同一个变量,以修复在循环中创建一个新实例的问题——而不仅仅是在它之前一次:

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

匿名用户

您正在修改同一个点对象。然而,由于您每次都更改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);

匿名用户

取值随机但不重复

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