使用java创建循环方块

Chr*_*win 6 java loops

完全披露:家庭作业.

说明:我无法理解我的老师.

问题:

编写一个调用的方法printSquare,它接受两个整数参数a min和a max,并以方形模式打印从包含minmax包含的数字 .方形图案通过示例比通过解释更容易理解,因此请查看下表中的示例方法调用及其生成的控制台输出.广场的每一行由一个在min和 之间增加整数的循环序列组成max.每行打印该序列的不同排列.第一行以min开头,第二行以with开头min + 1,依此类推.当任何一行中的序列到达时max,它会回绕到min.您可以假设该方法的调用者将传递a min和amax 参数min小于或等于max

在此输入图像描述

我不能为我的生活弄清楚如何使数字停在'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);
}
Run Code Online (Sandbox Code Playgroud)

我知道我使用了两次行,但它是我可以让编译器用循环形成方形的唯一方法.有人甚至远程了解我想要做什么吗?:/

rol*_*lfl 10

这实际上是一个很好的数学问题.假设:

int side = to - from + 1; /// the size/width of the square.
Run Code Online (Sandbox Code Playgroud)

square(row,col)中任意一点的值为:

from + ((row + col) % side)
Run Code Online (Sandbox Code Playgroud)

你应该能够把它放在你的循环中并"吸烟".


根据评论要求解释进行编辑.

诀窍是循环遍历'矩阵'中的所有位置.鉴于矩阵是方形的,循环相对简单,只有两个遍历系统的循环(嵌套):

    final int side = to - from + 1;
    for (int row = 0; row < side; row++) {
        for(int col = 0; col < side; col++) {
            ... magic goes here....
        }
    }
Run Code Online (Sandbox Code Playgroud)

现在,在这个循环中,我们有变量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
Run Code Online (Sandbox Code Playgroud)

距离是行和列的总和......(行和列从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
Run Code Online (Sandbox Code Playgroud)

在这里,单元格中的值已超过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
Run Code Online (Sandbox Code Playgroud)

如果我们用"除以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
Run Code Online (Sandbox Code Playgroud)

现在,如果我们将这个'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
Run Code Online (Sandbox Code Playgroud)

从某种意义上说,你需要知道的是每个单元格的值是:

the from value plus the remainder when you divide the 'distance' by the width.
Run Code Online (Sandbox Code Playgroud)

这是我测试过的代码:

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));
}
Run Code Online (Sandbox Code Playgroud)

  • 使用[余数(模数)运算符](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op1.html)定期计算是一个非常聪明的解决方案!太好了! (4认同)