全面披露:家庭作业。
解释:我无法理解我的老师。
问题:
Write a method called
printSquare
that takes in two integer parameters, amin
and amax
, and prints the numbers in the range frommin
tomax
inclusive 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 betweenmin
andmax
. 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 amin
and amax
parameter such thatmin
is less than or equal tomax
我这辈子都想不出如何让数字停在“最大值”处并从行的中间重新开始。
这就是我目前所拥有的,抱歉,我在使用 for 循环时遇到了麻烦。
for(int i = 0; i < row; i++)
{
for(int d = 0; d < row; d++)
{
System.out.print(d+1);
}
System.out.println(i);
}
我知道我使用了 row 两次,但这是让编译器用循环形成方形的唯一方法。有没有人甚至远程理解我想做什么? :/
最佳答案
这实际上是一个很好的数学问题。假设:
int side = to - from + 1; /// the size/width of the square.
正方形(行,列)中任意一点的值为:
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)
。
每个单元格中的值是起始值(本例中为 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
现在,如果我们将这个“取模”结果添加到 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));
}
关于java - 用java创建一个循环正方形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19792523/