我有一个包含值的二维数组。示例如下:
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/