【发布时间】:2021-12-09 11:33:51
【问题描述】:
我生成从 0 到 90 的随机唯一整数:
public static int randomNumber() {
int min = 0;
int max = 90;
return min + (int) (Math.random() * ((max - min) + 1));
}
...并使用这些生成的整数来填充多维 3*5 数组:
int rows = 3;
int columns = 5;
int[][] array = new int[rows][columns];
public static void populateArray(int[][] array, int rows, int columns) {
for (int indexRow = 0; indexRow < rows; indexRow++) {
for (int indexColumn = 0; indexColumn < columns; indexColumn++) {
array[indexRow][indexColumn] = randomNumber();
}
}
}
... 这会生成如下内容:
56 64 22 38 78
73 18 69 39 70
49 24 3 49 25
但是,我希望数组中的固定数量,例如 5 个随机元素(不多于,不少于 5 个随机元素)始终为 0 ,像这样:
0 64 22 38 0
73 18 0 39 70
0 24 3 0 25
有什么方法可以实现吗?
【问题讨论】:
-
ThreadLocalRandom.current().ints(0, rows * columns).distinct().limit(5).forEach(i -> array[i / rows][i % rows] = 0);
标签: java arrays multidimensional-array