-4

我正在做一个项目,使游戏板的三个空间与其他空间不同(+1、+2、-1)我需要将这些值添加到存储在 ArrayList 索引处的变量中。我可以找到一些东西来生成索引的数字,但我不知道如何确保它们处于唯一索引处。(它不能将所有三个值放在一个空格中)

如何在 0 到 16 范围内创建三个唯一的随机索引?

谢谢!

4

2 回答 2

2

将所有可能的数字放在一个列表中 - 将它们随机排列并取前三个:

public class Test {
  public void test() {
    System.out.println("Hello");
    List<Integer> numbers = new ArrayList<Integer>(Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16));
    Collections.shuffle(numbers);
    System.out.println(numbers);
  }

  public static void main(String args[]) {
    new Test().test();
  }
}

打印

[5, 12, 4, 7, 2, 11, 14, 9, 3, 0, 15, 8, 1, 10, 13, 16, 6]
于 2013-04-02T15:33:01.340 回答
1

试试这个从给定数字列表中生成唯一的随机数。

  1. 生成所有可能值的列表。
  2. 使用 Collections 中的 shuffle 方法对其进行随机播放Collections.shuffle(list);
  3. 通过在每个步骤中迭代获取项目。
于 2013-04-02T15:28:42.760 回答