Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flipping a multidimensional array java [closed]

I'm currently working on a Tetris AI, and I as looking for a method to flip a 4 by 4 multidimensional array. I've looked all over, and the most i could find was rotating, which wouldn't work in my case. From

o o o o 

o x x o

o x o o

o x o o 

to

o x o o

o x o o

o x x o

o o o o
like image 394
Echocage Avatar asked Sep 02 '25 17:09

Echocage


1 Answers

I don't know which dimension you need to flip, but this is one of them... Please note that this method destroys the original array! You didn't make your needs clear.

  • You didn't say which dimension needs to be flipped
  • You didn't say whether it should be in-place or create a new array

That said, here's one solution

public static void main(String args[]) {
    Integer[][] myArray = {{1, 3, 5, 7},{2,4,6,8},{10,20,30,40},{50,60,70,80}};

    // Before flipping  
    printArray(myArray);
    System.out.println();

    // Flip
    flipInPlace(myArray);

    // After flipping
    printArray(myArray);
}

public static void printArray(Object[][] theArray) {
    for(int i = 0; i < theArray.length; i++) {
        for(int j = 0; j < theArray[i].length; j++) {
            System.out.print(theArray[i][j]);
            System.out.print(",");
        }
        System.out.println();
    }
}

// *** THIS IS THE METHOD YOU CARE ABOUT ***
public static void flipInPlace(Object[][] theArray) {
    for(int i = 0; i < (theArray.length / 2); i++) {
        Object[] temp = theArray[i];
        theArray[i] = theArray[theArray.length - i - 1];
        theArray[theArray.length - i - 1] = temp;
    }
}

Produces:

1,3,5,7,
2,4,6,8,
10,20,30,40,
50,60,70,80,

50,60,70,80,
10,20,30,40,
2,4,6,8,
1,3,5,7,
like image 71
durron597 Avatar answered Sep 05 '25 07:09

durron597