Java,在任何方向循环遍历二维数组

标签 java arrays loops code-duplication

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

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

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 ...

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


编辑:在您编辑问题之前,我没有意识到您在谈论二维数组。您可以根据自己的需要进行调整。

关于Java,在任何方向循环遍历二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22543708/

相关文章:

java - 避免使用大量 Java 类共享字段的重复代码

php - 如何使用 PHP 获取此 JSON 中的所有 key ?

java - Spring表单绑定(bind)下拉对象

java - Dropwizard 仅在@POST 上验证字段

php - 如何在PHP中动态创建对象数组

python - 计算间隔之间的值数

reactjs - React 调用动态状态名称

c# - 迭代 IDictionary/Dictionary 对象

java - 为什么不重新评估 while 条件?

java - 为什么 sleep 方法会影响/不在面板上显示我更新的 JTextArea?