UndyingJellyfish - 6 months ago 39

Java Question

I want to create a matrix of size N by N where N is a constant value defined globally, for now I just want to create a matrix where N=6. Where I fall short is I want to make it diagonally, like so:

`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

Currently 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's only able to print 0 1 2 3 4 5 in every line, so I suppose I need another nested for-loop, however I'm not sure how to set it up.

Answer

`j`

is the column number, so it will be the same for all rows. What you need to do is to add or subtract `j`

from the line number, depending on the line number, in order to make a "shift". Since the result could become negative, you will need to add `N`

and *mod* by `N`

:

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

You can also rewrite it without an `if`

using a conditional expression:

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