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

时间:2014-03-20 19:54:34

标签: java arrays loops code-duplication

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

所以这个(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


这是我所拥有的sudo代码,如果' up'被迫;

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个副本(上,下,左,右),但我无法以其他方式弄清楚如何做到这一点。

2 个答案:

答案 0 :(得分:1)

如果您创建了一个长度相同的新数组并将元素复制到那里,该怎么办?然后你只需要迭代你的数组一次,使其成为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阵列。你可以根据自己的需要调整它。

答案 1 :(得分:1)

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

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

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

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("");
        }
    }
}