Java – creates an N by N diagonal matrix using basic logic

I want to create a matrix of N size, where n is a globally defined constant value. Now I just want to create a matrix of n = 6 Where am I, I want it diagonal, like this:

0 1 2 3 4 5
1 0 1 2 3 4
2 1 0 1 2 3
3 2 1 0 1 2
4 3 2 1 0 1
5 4 3 2 1 0

At present, I have this method:

public static void drawMatrix(){
    for (int line = 0; line < N; line++){
        for (int j = 0; j < N; j++){
            System.out.print(j + " ");
        }
        System.out.println();
    }
}

Unfortunately, it can only print 0 1 2 3 4 5 on each line, so I think I need another nested for loop, but I don't know how to set it

Solution

J is the column number, so it is the same for all rows What you need to do is add or subtract line numbers according to the line numbers in order to "move" Since the result may become negative, you need to add N and mod as N:

if (j > line) {
    System.out.print((N-line+j)%N + " ");
} else {
    System.out.print((line-j+N)%N + " ");
}

Demo.

If you use a conditional expression, you can also override it:

int sign = j > line ? -1 : 1;
System.out.print((N+sign*(line-j))%N + " ");

Demo.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>