Java中如何翻转多维数组

4

我正在开发一款俄罗斯方块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
3个回答

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,

+1 但是,如果你正在使用OpenGL,你可以通过基元将其旋转180度并镜像它。 - Igor
@Igor:我们无法知道他的问题的最佳解决方案是什么,因为他没有提供足够关于他需求的信息。 - durron597
我同意... 我们不知道他用数组做什么。 - Igor
它是二维的。我正在通过引用交换整个数组行。 - durron597

0

我不确定 flipping 的确切含义,但根据你的例子,可以通过以下方式实现结果

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接