java - 将二维数组移动到左循环

标签 java sorting multidimensional-array

我有一个包含值的二维数组。示例如下:

010101
101010
010101

I want to create a loop that shifts these values to the left like the example below.

101010
010101
101010

So the element that "falls off" goes back in to the end. I'm having a hard time solving this issue in code.

Anyone got any advice?

So far I have made it scroll but I have no clue how to get the elements that fall off to go back in.

This is what I have so far.

for (int row = 0; row < array.length; row++) {
    for (int col = 0; col < array[row].length; col++) {
        if (!(row >= array.length) && !(col >= array[row].length - 1)) {
            array[row][col] = array[row][col + 1];
        }
    }
}

最佳答案

尝试使用取模运算符:

arrayShifted[row][col] = array[row][(col + 1) % array[row].length];

同时删除您的条件检查。另请注意,为避免覆盖值,您需要将结果存储在新数组中。

for (int row = 0; row < array.length; row++) {
    for (int col = 0; col < array[row].length; col++) {
        arrayShifted[row][col] = array[row][(col + 1) % array[row].length]
    }
}

关于java - 将二维数组移动到左循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34276996/

相关文章:

php - 为什么我在以下场景中没有获得更新的数组?

java - 在 JBoss EAP 6.0.1 中更改端口号

java - 提交Flink作业时出现NoSuchMethodError

c# - C# (.NET) 中的 Android AsyncTask 类似功能

c# - 排序数字然后字符串 C#

algorithm - 用于维护已排序的 <5k 整数列表的内存效率最高的数据结构是什么?

C++:为我的类型定义了我自己的赋值运算符,现在 .sort() 不会对我的类型的 vector 起作用?

java - 将 AnchorPane 打印为 PNG

javascript - 转换为字符串时保留嵌套数组结构,JavaScript

java - 存储具有 K-V 列的表的最佳数据结构是什么