Filling 2D array diagonally

Advertisements

I’ve been trying to get a 10×10 2D array filled diagonally as in the image below for a couple hours now, but after checking every possible way to use rows and collums I still can’t seem to identify my misunderstanding of the code.

What im supposed to get:

this is how far ive gotten, i dont understand what im doing wrong

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

>Solution :

You first need to loop your rows, and knowing that it’s a diagonal loop, the starting point at each step will be the (i, i) tuple. Starting from there, an inner loop loops up to 2 further elements and updates the values at the given place if they are inside bounds. Whenever we set a value to a given element, we decrement currentIndex, so we will not have to worry about its value.

import java.util.*;
import java.lang.*;
import java.io.*;

// The main method must be in a class named "Main".
class Main {
    public static void main(String[] args) {
        int currentIndex = 27;
        int[][] array = new int[10][10];
        for (int i = 0; i < array.length; i++) {
            for (int j = i; j <= i + 2 && (j < array[i].length); j++) {
                array[i][j] = currentIndex--;
            }
        }
        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array.length; j++) {
                System.out.print((array[j][i] > 9 ? "" : " ") + array[j][i] + " ");
            }
            System.out.println();
        }
    }
}

https://www.mycompiler.io/view/0rg7WTh30b9

Leave a ReplyCancel reply