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
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.
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,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With