gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:40:32 25 4
gpt4 key购买 nike

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

010101101010010101

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

101010010101101010

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com