Search code examples
javaarraysmultidimensional-array2ddiagonal

How to fill a 2D array diagonally


I have a 2D char array that I need to fill with color codes to create synthetic images that have patterns. The array is filled with zeros, which end up returning a black image if run through a separate program. I need to fill the array diagonally (in this direction ) with (char)255 (a color code that represents white on this separate program). This will produce an image with alternating black and white lines that are diagonal in direction. I need to use a nested for loop to accomplish this, but I'm not sure how to set (char)255 to different elements across the 2D array diagonally. It's confusing me. Please help.

here is the 2D array:

(0,0) (0,1) (0,2) (0,3) (0,4)

(1,0) (1,1) (1,2) (1,3) (1,4)

(2,0) (2,1) (2,2) (2,3) (2,4)

(3,0) (3,1) (3,2) (3,3) (3,4)

(4,0) (4,1) (4,2) (4,3) (4,4)

the elements in the array that need to be assigned (char)255 are (4,0), (2,0) (3,1) (4,2), (0,0) (1,1) (2,2) (3,3) (4,4), (0,2) (1,3) (2,4), and (0,4).

Here is code I did for a horizontal line if it helps understand my problem:

public static char[][] createVerticalStripes(int height, int width, int stripeWidth) {

    // Declaring array for this method

    char[][] image = new char[height][width];

    for (int rows = 0; rows < height; ++rows) {

        for (int columns = 0; columns < width; ++columns) {

            if (columns % stripeWidth == 0) {
                image[rows][columns] = (char) 255;
            }
        }
    }

    return image;
} 

Solution

  • Do you mean something like this? (Assuming the size of your array is 5X5)

    class Diagonal {
        static char [][] colorArray = new char [5][5];
        public static void main(String args[])
        {
            for (int i = 0; i < 5; i++ ) {
                // Even rows, including 0th row
                if ((i%2)==0) {
                    // Color in locations with even indexes
                    for (int j =0; j < 5; j++ ) {
                        if ((j%2)==0) {
                            colorArray[i][j] = 255;
                        }
                    }
                } else { // Odd rows
                    for (int j =0; j < 5; j++ ) {
                        // Color in locations with odd indexes
                        if ((j%2)!=0) {
                            colorArray[i][j] = 255;
                        }
                    }
                }
            }
    
        }
    }