翻转多维数组java [英] Flipping a multidimensional array java

查看:172
本文介绍了翻转多维数组java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究俄罗斯方块AI,我正在寻找一种方法来翻转一个4乘4的多维数组。我看了一遍,我能找到的最多是旋转,这在我的情况下是行不通的。
来自

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 

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

产生:

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,

这篇关于翻转多维数组java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆