简体   繁体   English

递减数字的嵌套for循环问题

[英]Nested for-loop problem with descending number

I'm trying to figure out how to complete this problem.我试图弄清楚如何完成这个问题。 I'm shooting for:我正在拍摄:

3 3 3 3 3 
3 2 2 2 3
3 2 1 2 3
3 2 2 2 3
3 3 3 3 3

and I have the following code, which gives me this:我有以下代码,它给了我这个:

3 2 1 
3 2 1 
3 2 1
3 2 
3 

I think I'm close but can some one help?我想我已经很接近了,但有人可以帮忙吗?

    System.out.print("Enter the length of the pattern size: ");
    int size = scan.nextInt();
    System.out.println();
    for (int row=size*2-1; row >= 1; row--) { 
        for (int col=size*2-1; col >= 1; col--) {
            if (col <= size && row >= size-col+1 )
                System.out.print(col + " ");
        }
        System.out.println();
    }
}

} }

I think the problem is with the logic you used.我认为问题在于您使用的逻辑。 I made an algorithm inspired by another idea, maybe it will help you.我做了一个受另一个想法启发的算法,也许它会对你有所帮助。 I am sure there is an easier way then this, but this works as well with all numbers.我相信有比这更简单的方法,但这也适用于所有数字。

example for input 4: get x and y value and after the smallest coordinate(either x or y) is the indicator which number should be printed.输入 4 的示例:获取 x 和 y 值,在最小坐标(x 或 y)之后是应该打印哪个数字的指示符。 x and y increases from the top left corner downwards starting from 0. x 和 y 从 0 开始从左上角向下增加。

If x or y coordinate is 0 for example we know it is going to be 4. if x coordinate is 2 but y is 3, we still take the smaller one: the number printed out will be in the second circle of numbers, number 2.例如,如果 x 或 y 坐标为 0,我们知道它将为 4。如果 x 坐标为 2 但 y 为 3,我们仍然取较小的那个:打印出来的数字将在第二个数字圈中,数字 2 .

// 4 4 4 4
// 4 3 3 3
// 4 3 2 2
// 4 3 2 1

System.out.print("Enter the length of the pattern size: ");
int size = scan.nextInt();
System.out.println();

int len = size*2-1; // length of column and row

for (int row = 0; row < len; row++) {

    int x = (row%size); // get x coordinate (row)
    if (row >= size) x = (size-2) - x; // flip coordinate

    for (int col = 0; col < len; col++) {
        int y = (col%size); // get y coordinate (col)
        if (col >= size) y = (size-2) - y; // flip coordinate

        int val = size - Math.min(x, y); // get minimum coordinate
        System.out.print(val + " ");
    }

    System.out.println();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM