2012-11-07 56 views
3

我目前正在研究一个俄罗斯方块AI,而我正在寻找一种方法来翻转一个4乘4的多维数组。我已经找遍了,最能找到的是旋转的,这对我来说不起作用。 从翻转一个多维数组java

o o o o 

o x x o 

o x o o 

o x o o 

o x o o 

o x o o 

o x x o 

o o o o 

回答

3

我不实现不知道你需要翻转哪一个维度,但是这是其中之一......请注意,这种方法破坏了原始数组!你没有明确你的需求。

  • 你没有说需要哪些维度翻转
  • 你没有说是否应该就地或创建一个新的阵列

这就是说,这里有一个解决方案

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, 
+0

+1但是,如果你使用OpenGL,你可以通过180将其旋转和镜像它们它使用基元。 – Igor

+0

@Igor:没有办法知道他的问题最好的解决方案是什么,因为他没有给我们足够的关于他的要求的信息 – durron597

+0

我同意......我们不知道他在用什么阵列为 – Igor

0

我不知道是什么意思翻转究竟,但基于您的例子,其结果可能做

temp = array[0]; 
array[0] = array[3]; 
array[3] = temp; 
temp = array[1]; 
array[1] = array[2]; 
array[2] = temp; 
0

你可以编写类似的信息(伪代码,我没有做过的Java的年龄,但你的想法)

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