说明:我无法理解我的老师.
问题:
Write a method called
printSquarethat takes in two integer
parameters,aminand amax,and prints the numbers in the range frommintomaxinclusive in a square pattern. The square pattern is
easier to understand by example than by explanation,so take a look at
the sample method calls and their resulting console output in the
table below. Each line of the square consists of a circular sequence
of increasing integers betweenminandmax. Each line prints a
different permutation of this sequence. The first line begins with
min,the second line begins withmin + 1,and so on. When the
sequence in any line reachesmax,it wraps around back tomin. You
may assume the caller of the method will pass aminand amax
parameter such thatminis less than or equal tomax
我不能为我的生活弄清楚如何使数字停在’max’值并从线的中间重新开始.
这是我到目前为止,道歉,但我遇到for循环的问题.
for(int i = 0; i < row; i++)
{
for(int d = 0; d < row; d++)
{
System.out.print(d+1);
}
System.out.println(i);
}
我知道我使用了两次行,但它是我可以让编译器用循环形成方形的唯一方法.有人甚至远程了解我想要做什么吗? :/
解决方法
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));
}