I.ve got 2D array amount of raws and columns are the same.
I need to fill diagonal elements like this:
1 0 1
0 1 0
1 0 1
Here is my code:
private static void fillDiagonal() {
int[][] arr = new int[3][3];
// System.out.println(Arrays.deepToString(arr));
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
arr[i][i] = 1;
arr[0][2] = 1;
arr[2][0] = 1;
}
}
System.out.println(Arrays.deepToString(arr));
}
It’s worked, but I need to change it from Hardcode values.
arr[0][2] = 1;
arr[2][0] = 1;
To fill it with loop
How to achieve it?
>Solution :
There is no need for two for loops. You can do this in O(n), as for values on the diagonal y and x will be identical.
To get both diagonals you need to start once on the left using i and once on the right using arr.length - i - 1. As i is increasing you will gradually move from left to right for i and at the same time move from right to left for arr.length - i - 1.
This will work for any n x n matrix.
private static void fillDiagonal() {
int[][] arr = new int[5][5];
for (int i = 0; i < arr.length; i++) {
arr[i][i] = 1;
arr[arr.length - i - 1][i] = 1;
}
Arrays.stream(arr).map(Arrays::toString).forEach(System.out::println);
}
Expected output:
[1, 0, 0, 0, 1]
[0, 1, 0, 1, 0]
[0, 0, 1, 0, 0]
[0, 1, 0, 1, 0]
[1, 0, 0, 0, 1]