-1

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;
} 
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Collecto
  • 89
  • 9
  • What exactly your problem is? You do not know how to assign value to array element? – talex Nov 02 '16 at 16:54
  • Well, what does *diagonally* mean? Explain that to me in English. If you manage to do that, putting it into code shouldn't be hard. – RaminS Nov 02 '16 at 16:54

1 Answers1

0

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;
                    }
                }
            }
        }

    }
}
David Choweller
  • 1,060
  • 1
  • 8
  • 7