gpt4 book ai didi

java - 如何将某个值添加到二维数组中的随机 block ?

转载 作者:行者123 更新时间:2023-11-29 05:16:06 24 4
gpt4 key购买 nike

我想做的是给数组中的两个随机点分配一个数字(比如 2)。以下是我设置阵列的方式。

public static void print_array(int[][] array) {
for (int row = 0; row < array.length; row++) {
System.out.print("\n-----------------\n" +
"| ");
for (int col = 0; col < array[row].length; col++) {
if (col != array[row].length) {
System.out.print(array[row][col] + "| ");
if (col == array[row].length) {
System.out.print("\n");
}
}
}
}
System.out.print("\n-----------------");
}

然后我在 main 方法中调用 print_array 来显示数组。然后添加我需要使用此方法的数字:

public static void placeBlock(int[][] array) {
}

我怎样才能把一个整数放在数组的随机位置?

最佳答案

您可以使用模运算符。该运算符返回余数。例如。

2 % 3 returns 2 (It is lesser that 3 the second operand)
3 % 3 returns 0 (It is lesser that 3 the second operand)
3 % 2 returns 1 (It is lesser that 2 the second operand)

假设您有 2 个随机数 num1 和 num2,并且您知道二维数组的维度是 MxN。即M行N列。所以当你这样做的时候

num1 % M returns a number between 0...M
num2 % N returns a number between 0...N

这使您能够:

array[num1%M][num2%N]=2;

根据评论编辑:如果您要生成随机数,则:

Random randomGenerator=new Random();
int num1 = randomGenerator.nextInt(array.length);
int num2 = randomGenerator.nextInt(array[0].length);

在这种情况下,您会根据长度获得随机数,因此您可以直接使用它

array[num1][num2]=2;

关于java - 如何将某个值添加到二维数组中的随机 block ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26492690/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com