这实际上是一个很好的数学问题.假设:
int side = to - from + 1; /// the size/width of the square.
square(row,col)中任意一点的值为:
from + ((row + col) % side)
你应该能够把它放在你的循环中并“吸烟”.
根据评论要求解释进行编辑.
诀窍是循环遍历’矩阵’中的所有位置.鉴于矩阵是方形的,循环相对简单,只有两个遍历系统的循环(嵌套):
final int side = to - from + 1;
for (int row = 0; row < side; row++) {
for(int col = 0; col < side; col++) {
... magic goes here....
}
}
现在,在这个循环中,我们有变量row和col,它们代表我们感兴趣的矩阵中的单元格.该单元格中的值需要与它与原点的距离成正比…..让我解释一下….如果原点是左上角(它是),那么与原点的距离是:
0 1 2 3 4
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
距离是行和列的总和……(行和列从0开始计数).
我们在每个矩阵中放置的值仅限于固定范围.对于上面的示例,使用大小为5的正方形,可以将其指定为printSquare(1,5).
每个单元格中的值是from值(本例中为1)加上距离原点的距离…天真地看起来像:
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
5 6 7 8 9
在这里,单元格中的值已超过5的限制,我们需要将它们包裹起来…所以,诀窍是“包裹”距离原点的距离…..并且“模数”运算符很棒为了那个原因.首先,考虑原始的“原点距离”矩阵:
0 1 2 3 4
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
如果我们用“除以5的剩余距离”(模5或%5)来填充此矩阵,我们得到矩阵:
0 1 2 3 4
1 2 3 4 0
2 3 4 0 1
3 4 0 1 2
4 0 1 2 3
现在,如果我们将这个’modulo’结果添加到from值(1),我们得到我们的最终矩阵:
1 2 3 4 5
2 3 4 5 1
3 4 5 1 2
4 5 1 2 3
5 1 2 3 4
从某种意义上说,你需要知道的是每个单元格的值是:
the from value plus the remainder when you divide the 'distance' by the width.
这是我测试过的代码:
public static final String buildSquare(final int from, final int to) {
final StringBuilder sb = new StringBuilder(side * side);
final int side = to - from + 1;
for (int row = 0; row < side; row++) {
for(int col = 0; col < side; col++) {
sb.append( from + ((row + col) % side) );
}
sb.append("\n");
}
return sb.toString();
}
public static void main(String[] args) {
System.out.println(buildSquare(1, 5));
System.out.println(buildSquare(3, 9));
System.out.println(buildSquare(5, 5));
System.out.println(buildSquare(0, 9));
System.out.println(buildSquare(0, 3));
}