flipping a multi-dimensional array java

arrays, java, multidimensional-array

Solution

This should suit your needs:

public static char[][] mirror(int width, int height, char[][] in) {
    char[][] out = new char[height][width];
    for (int i = 0; i < height; i++) {
        for (int j = 0; j < width; j++) {
            out[i][width - j - 1] = in[i][j];
        }
    }
    return out;
}

For example:

char[][] in = new char[][] {
    new char[] { '#', '#', '#', '~' },
    new char[] { '~', '#', '~', '~' },
    new char[] { '~', '#', '~', '~' },
    new char[] { '~', '~', '~', '~' },
    new char[] { '~', '~', '~', '~' }
};

for (char[] line : mirror(4, 5, in)) {
    for (char row : line) {
        System.out.print(row);
    }
    System.out.println();
}

Prints:

~###
~~#~
~~#~
~~~~
~~~~

Problem

i have a class that creates a canvas of characters with a desired width and height. within this i have a method drawLetter() (which basically changes the characters so that a letter appears on the canvas (like very simple ASCII art) i have 3 other methods rotateClockwise, flipHorizontal, and flipVertical rotate and flipHorizontal i have done fine and they work but i cannot seem to work out where im going wrong with flipping the array vertically (out of interest i think i have horizontal and vertical the wrong way round but ill put a sample of what im trying to get done below) this is what i cant work out: this: ``` # # # ~ ~ # ~ ~ ~ # ~ ~ ~ ~ ~ ~ ``` to this: ``` ~ # # # ~ ~ # ~ ~ ~ # ~ ~ ~ ~ ~ ``` obviously it will be done in a for loop like my other methods, below i will post the method i have done already for horizontal and rotate clockwise to prove its not homework i cant do ``` void mirrorHorizontally() { char[][]horizontalImage = new char[height][width]; for (int i = 0; i < height /2; i++) { for(int j = 0; j < width; j++) { horizontalImage[height - (i+1)][j] = canvasArray[i][j]; horizontalImage[i][j] = canvasArray[height - (i+1)][j]; } } printPicture(horizontalImage); } void rotateClockwise() { char[][] rotatedImage = new char[height][width]; for(int i=0; i< canvasArray.length; i++) { for(int j= canvasArray.length-1; j >= 0; j--) { rotatedImage[i][rotatedImage.length-1-j] = canvasArray[j][i]; } } printPicture(rotatedImage); } ``` canvasArray is the original image out of interest in a char[][] class variable

Original source