Home > Enterprise >  Fill diagonal elements of array with Numbers
Fill diagonal elements of array with Numbers

Time:03-25

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?

CodePudding user response:

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]

CodePudding user response:

First, notice that you set those two entries for every iteration of the loops, which is bad. Second, you have a double-nested loop where you don't even use j, so that's bad. Think about this: You want to set 3 entries on the main diagonal and 3 entries on the reverse diagonal. So that should just require one or two loops that execute 3 times, not a double-nested loop. Third, you realized that the important indices are [0][0],[1][1], and [2][2], which you can index as [i][i] if you make i go from 0 to 2. Now what are the indices in the reverse diagonal? Write them down, and then create a formula based on i and 3 (or in general n) that will be the correct ones.

CodePudding user response:

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  ) {
                if(i == j) arr[i][j] = 1;
                if(i j == arr.length - 1) arr[i][j] = 1;
            }
        }
        System.out.println(Arrays.deepToString(arr));
    }
  • Related