当我做2D阵列随机图像时,有重复,我怎样才能让它独一无二?

时间:2018-03-06 23:11:47

标签: java javafx

我不想发布我的完整代码作为它的大,但基本上这是一个随机化2D图像数组的函数的一部分,唯一的问题是这里是同一图像的许多重复,我在希望为每个行和列提供一个独特的图片。我该怎么做才能解决这个问题?

  Random r= new Random();
    int rand1, rand2;
    for (int r = 0; r < 4; r++) {
        rand1= rand.nextInt((3 - 0) + 1) + 0;
        for (int c = 0; c < 4; c++) {
            rand2= rand.nextInt((3 - 0) + 1) + 0;
            Button b = new Button();
            b.setGraphic(new ImageView(new Image(getClass().getResourceAsStream(images+ rand1+ rand2+ ".png"))));
            grid[r][c] = b;
        }
    }

1 个答案:

答案 0 :(得分:0)

以下是以随机顺序绘制所有唯一组合的解决方案,采用以下文件名:

@Test
public void combinations() {
    int[] prefixes = new int[]{ 0, 1, 2, 3, 4 };
    int[] suffixes = new int[]{ 0, 1, 2, 3, 4, 5 };

    List<String> literals = new ArrayList<>();
    for (int prefix: prefixes) {
        for (int suffix: suffixes) {
            literals.add("" + prefix + suffix);
        }
    }

    Random random = new Random();
    while (!literals.isEmpty()) {
        String literal = literals.remove(random.nextInt(literals.size()));
        System.out.println(literal);
    }
}

打印:

23
04
25
35
43
41
05
20
45
31
11
01
10
34
14
12
22
44
30
33
02
03
24
15
00
32
42
13
21
40

正如其他地方所建议的那样,您也可以运行Collections.shuffle(literals),然后按顺序遍历列表:

Collections.shuffle(literals);

for (String literal: literals) {
    System.out.println(literal);
}
05
33
35
25
31
14
22
23
45
40
32
15
02
04
30
12
00
11
44
24
42
13
41
21
20
10
03
34
01
43