这是创建魔方的方法的代码。 n
是正方形的长度。它必须看起来像:
static int[][] magicSquare(int n) {
int [] [] square = new int [n] [n];
我不理解这个k=(k+1)%n;
,尤其是为什么%n
?是不是每次循环都将k
放到1
?
for (int i=0; i<n; i++){
in k=i;
for (int j=0; j<n; j++){
square[i][j]=k+1;
k=(k+1)%n;
1 2 3 4
2 3 4 1
3 4 1 2
4 1 2 3
答案 0 :(得分:1)
Java中的%用于模块化划分。每当应用运算符时,右手操作数将从左手操作数中减去多少次,剩下的将是输出。您可以通过将左侧操作数除以右侧操作数来轻松检查它,并将剩余的整数作为整数。在a%b
的情况下,它会是这样的
a - (a/b)*b
。
以下是一些例子:
10 % 4 = 2 // 2*4 = 8 + 2 = 10
10 % 5 = 0 // 2*5 = 10 + 0 = 10
0 % 4 = 0 // result here is 0 thus 0*4 = 0 + 0 = 0
// if you try to extract 4 from 0, you will not succeed and what's left will be returned (which was originally 0 and it's still 0)...
在你的情况下:
k = (k + 1) % n;
确保k的值永远不会超过4,因此如果它可以被4分割,那么它将被分割并且剩余的将被写入那里。在k恰好为4的情况下,将值0写入k,但由于您总是添加k + 1
,因此将值写为1.
对于初学者,我建议打印您感兴趣的值,并观察数据是如何迁移的。在这里,我为您添加了一些printlns以获得想法。运行代码并自行测试。我相信事情会变得更清洁。
public static void main(String[] args) {
int n = 4;
int[][] square = new int[n][n];
System.out.println("--------------");
for (int i = 0; i < n; i++) {
int k = i;
System.out.println("Filling magic cube line " + (i + 1) + ". The k variable will start from " + i + "."); // i initial value is 0 so we add 1 to it just to get the proper line number.
for (int j = 0; j < n; j++) {
System.out.println("Filling array index [" + i + "][" + j + "] = " + (k + 1)); // array indexes start from 0 aways and end at array.length - 1, so in case of n = 4, last index in array is 3.
square[i][j] = k + 1; // add 1 to k so the value will be normalized (no 0 entry and last entry should be equal to n).
k = (k + 1) % n; // reset k if it exceeds n value.
}
System.out.println("--------------");
}
Arrays.stream(square).forEach(innerArray -> {
Arrays.stream(innerArray).forEach(System.out::print);
System.out.println();
});
}
您可以随时玩游戏并重构代码,如下所示:
public static void main(String[] args) {
int n = 4;
int[][] square = new int[n][n];
System.out.println("--------------");
for (int i = 1; i <= n; i++) {
int k = i;
System.out.println("Filling magic cube line " + i + ". The k variable will start from " + i + ".");
for (int j = 0; j < n; j++) {
System.out.println("Filling array index [" + (i - 1) + "][" + (j - 1) + "] = " + k); // array indexes start from 0 aways and end at array.length - 1, so in case of n = 4, last index in array is 3. Subtract both i and j with 1 to get the proper array indexes.
square[i - 1][j - 1] = k;
k = (k + 1) % n; // reset k if it exceeds n value.
}
System.out.println("--------------");
}
Arrays.stream(square).forEach(innerArray -> {
Arrays.stream(innerArray).forEach(System.out::print);
System.out.println();
});
}
请记住,数组的索引从0开始并以长度结束 - 1.在4的情况下,第一个索引为0,最后一个为3.这是两个实现的差异,试着看看如何索引和值取决于控制变量i
和j
。
https://www.diffchecker.com/x5lIWi4A
在第一种情况下,i和j都从0开始并且一直在增长,直到它们的值都小于n,而在第二种情况下,它们从1开始并且一直在增长直到它们等于n。我希望现在越来越清楚了。干杯