Home > Back-end >  Two-dimensional array task that I can't solve
Two-dimensional array task that I can't solve

Time:11-12

Recently I started learning two-dimensional arrays and recently I came across these tasks that give you images of a 10 x 10 array and you have to recreate it. I completed some tasks but one task gave me a problem. Seems like I am really close but at the same time not. I have tried for some time now but I can't get the needed answer.

The task that I have to recreate - picture.

How far I have got - picture.

  public static void main(String[] args) {
    
    int A[][] = new int [10][10];

    for (int i = 0;  i <= 9; i  ) {
      for (int j=9-i, n=1; j>=1; j--) {
        if (j <= 9) {
          A[i][j] = n  ;
        }
      }
    }

    for (int i=0; i<10; i  ) {
      for (int j=0; j<10; j  ) {
        System.out.print(A[i][j] "\t");
      }
      System.out.println();
    }
  }
} 

Thanks for helping!

CodePudding user response:

The desired pattern is symmetric to the main diagonal, that is for a pair od indexes i and j these cells should have the same contents: a[i][j] = a[j][i].

Next, when iterating the start number decreases by 2 for the elements on the main diagonal: 9, 7, 5, 3, 1, and the "width" of the nested loop is reducing from both sides.

So the resulting code may look like this:

int A[][] = new int [10][10];

for (int i = 0; i < 10 / 2; i  ) {
    for (int j = i; j < 10 - i; j  ) {
        A[i][j] = A[j][i] = 9 - i - j;
    }
}

Output:

9   8   7   6   5   4   3   2   1   0   
8   7   6   5   4   3   2   1   0   0   
7   6   5   4   3   2   1   0   0   0   
6   5   4   3   2   1   0   0   0   0   
5   4   3   2   1   0   0   0   0   0   
4   3   2   1   0   0   0   0   0   0   
3   2   1   0   0   0   0   0   0   0   
2   1   0   0   0   0   0   0   0   0   
1   0   0   0   0   0   0   0   0   0   
0   0   0   0   0   0   0   0   0   0   

CodePudding user response:

Here is another version. It fills the arrays from the bottom up.

  • first, loop from 9 to 0
  • then assign a new Array to the ith cell in A
  • the simply loop starting to fill up the arrays.
for (int i = 9; i >= 0; i--) {
   A[i] = new int[10];
   for (int k = 9-i,z = 0; k > 0; k--) {
      A[i][z  ] = k;
   }
}

for (int[] arr : A) {
    System.out.println(Arrays.toString(arr));
}

Prints

[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
[8, 7, 6, 5, 4, 3, 2, 1, 0, 0]
[7, 6, 5, 4, 3, 2, 1, 0, 0, 0]
[6, 5, 4, 3, 2, 1, 0, 0, 0, 0]
[5, 4, 3, 2, 1, 0, 0, 0, 0, 0]
[4, 3, 2, 1, 0, 0, 0, 0, 0, 0]
[3, 2, 1, 0, 0, 0, 0, 0, 0, 0]
[2, 1, 0, 0, 0, 0, 0, 0, 0, 0]
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
  • Related