1

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

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

谢谢

4

3 回答 3

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();
于 2012-04-16T21:49:09.740 回答
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);
于 2012-04-16T21:49:01.470 回答
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));
于 2019-02-22T11:19:41.373 回答