我正在开发一款俄罗斯方块AI,需要用到翻转一个4x4的多维数组。经过查找,我发现大多数资料都是关于旋转的,而在我的情况下无法使用。请问有没有其他方法可以实现?
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
我正在开发一款俄罗斯方块AI,需要用到翻转一个4x4的多维数组。经过查找,我发现大多数资料都是关于旋转的,而在我的情况下无法使用。请问有没有其他方法可以实现?
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
话虽如此,这里有一个解决方案
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;
}
}
产生:
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,
我不确定 flipping 的确切含义,但根据你的例子,可以通过以下方式实现结果
temp = array[0];
array[0] = array[3];
array[3] = temp;
temp = array[1];
array[1] = array[2];
array[2] = temp;
function flipGridVertically(gridToFlip){
Array gridToReturn;
//start from the bottom row (gridToFlip.size is the vertical size of the grid)
//size is the horizontal size of the grid.
for (counter=gridToFlip.size-1; counter>0; counter--)
//start the second loop from the top
for (counter2=0;counter2<gridToFlip.size;counter2++)
gridToReturn[counter2] = gridToFlip[counter];
return gridToReturn;
}