使用随机数生成数组

bem*_*bas 1 java arrays

我想在java中生成一个从1到10的随机数的数组,但我需要数组至少有10个数中的一个.

错了:array = {1,2,3,1,3,2,4,5}

正确的:array = {1,2,4,3,6,8,7,9,5,10...}

阵列的大小可以大于10,但阵列中必须存在0到10个数字.

到目前为止我生成数组的代码:

public int[] fillarray(int size, int Reel[]) {

    for (int i = 0; i < size; i++) {
        Reel[i] = (int) (Math.random() * symbols);
    }

    System.out.println(Arrays.toString(Reel));

    return Reel;
}
Run Code Online (Sandbox Code Playgroud)

Ole*_*hov 10

你可以使用ListCollections.shuffle:

List<Integer> list = new ArrayList<>(List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
Collections.shuffle(list);
Run Code Online (Sandbox Code Playgroud)

并且,根据@ Elliott的有用建议,您可以将列表转换为数组:

int[] result = list.stream().mapToInt(Integer::intValue).toArray();
Run Code Online (Sandbox Code Playgroud)

  • `List`没有固定的大小. (3认同)