繁体   English   中英

Java,在任何方向上循环遍历2d数组

[英]Java, loop through 2d array in any direction

我正试图在指定的任何方向上移动二维数组中的元素。 换句话说,如果按下左键,阵列的每个元素都会向左移动尽可能远。

所以这(0表示一个空的空间),

1 0 2 0
0 3 0 1
1 0 6 9
1 0 0 0

会成为

1 2 0 0
3 1 0 0
1 6 9 0
1 0 0 0


如果按下'up',这就是我所拥有的sudo代码;

for col = 0 to SIZE
   for i = 0 to SIZE - 1
      if array[i][col] == 0
         for j = i to SIZE
            if array[j][col] != 0
               array[i][col] = array[row][j]
               array[j][col] = 0
               break

实际的代码是一个更长的(即检查两个相同的元素碰撞)我不想有这部分代码的4个副本(上,下,左,右),但我无法弄清楚怎么做任何其他方式。

如果你制作了一个相同长度的新数组并将元素复制到那里怎么办? 然后你只需要迭代你的数组一次,使它成为O(n)

//This would be your array
int[] things = new int[]{1,23,4,54,234,54,1};

//Create a new array that is the same length
int[] shiftedThings = new int[things.length];

//These are for our loop
int start;
int end;

//If its an up shift
if(shiftUp){
    //Copy the last element into the first for an up shift
    shiftedThings[0] = things[things.length-1];

    //Start from the 2nd element, since we've already copied over the first
    start = 1;
    end = shiftedThings.length;
}   
else{
     //Copy the first element to the end for a down shift
     shiftedThings[shiftedThings.length-1] = things[0];

     start = 0;

     //End at 1 element before the end, since we've already copied over the last element
     end = shiftedThings.length-1;
} 

while(start < end){
    if(shiftUp)
        shiftedThings[index] = things[index-1];
    else
        shiftedThings[index] = things[index+1];
    start++;
}

//shiftedElements is now ready to be printed or returned or ...

可能有一个比这更优雅的解决方案。


编辑:在您编辑问题之前,我没有意识到您正在谈论2D阵列。 您可以根据自己的需要进行调整。

虽然技术上可以用相同的方法覆盖所有这些移位操作,但它可能不像为每个方向创建专用方法那样容易理解(并且不那么有效)。

一方面,对于一个真正的程序员来说,这是一种羞辱和破碎,但另一方面......嘿,你可以肯定,永远不会超过这四个方向。

或者......好吧,对角线,也许吧? ;-)

public class ArrayShiftTest
{
    public static void main(String[] args)
    {
        int array[][] = new int[][]
        {
            { 1, 0, 2, 0 },
            { 0, 3, 0, 1 },
            { 1, 0, 6, 9 },
            { 1, 0, 0, 0 },
        };

        System.out.println("Original");
        print(array);

        System.out.println("Left");
        int arrayL[][] = clone(array);
        shift(arrayL,  0, -1);
        print(arrayL);

        System.out.println("Right");
        int arrayR[][] = clone(array);
        shift(arrayR,  0,  1);
        print(arrayR);

        System.out.println("Up");
        int arrayU[][] = clone(array);
        shift(arrayU, -1,  0);
        print(arrayU);

        System.out.println("Down");
        int arrayD[][] = clone(array);
        shift(arrayD,  1,  0);
        print(arrayD);

        // Bonus :-) :

        System.out.println("Left Up");
        int arrayLU[][] = clone(array);
        shift(arrayLU,  -1, -1);
        print(arrayLU);

        System.out.println("Right Up");
        int arrayRU[][] = clone(array);
        shift(arrayRU,  -1,  1);
        print(arrayRU);

        System.out.println("Left Down");
        int arrayLD[][] = clone(array);
        shift(arrayLD,   1, -1);
        print(arrayLD);

        System.out.println("Right Down");
        int arrayRD[][] = clone(array);
        shift(arrayRD,   1,  1);
        print(arrayRD);

    }

    private static void shift(int array[][], int dr, int dc)
    {
        boolean shifted = true;
        while (shifted)
        {
            shifted = false;
            for (int r=0; r<array.length; r++)
            {
                for (int c=0; c<array[r].length; c++)
                {
                    if (array[r][c] != 0)
                    {
                        shifted |= shift(array, r, c, dr, dc);
                    }
                }
            }
        }
    }

    private static boolean shift(int[][] array, int r, int c, int dr, int dc)
    {
        int value = array[r][c];
        array[r][c] = 0;
        int cr = r;
        int cc = c;
        while (isValid(array, cr, cc))
        {
            int tr = cr + dr;
            int tc = cc + dc;
            if (!isValid(array, tr, tc) || array[tr][tc] != 0)
            {
                break;
            }
            cr = tr;
            cc = tc;
        }
        array[cr][cc] = value;
        return cr != r || cc != c;
    }

    private static boolean isValid(int array[][], int r, int c)
    {
        return r>=0 && r<array.length && c>=0 && c<array[r].length;
    }

    private static int[][] clone(int array[][])
    {
        int result[][] = array.clone();
        for (int r=0; r<array.length; r++)
        {
            result[r] = array[r].clone();
        }
        return result;
    }

    private static void print(int array[][])
    {
        for (int r=0; r<array.length; r++)
        {
            for (int c=0; c<array[r].length; c++)
            {
                System.out.printf("%3d", array[r][c]);
            }
            System.out.println("");
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM