Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shifting a 2D array to the left loop

I have a 2D array with values in it. Example below:

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];
        }
    }
}
like image 342
Lithicas Avatar asked Jan 26 '26 00:01

Lithicas


1 Answers

Try using the modulus operator:

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

Remove your condition check as well. Also note, to avoid overwriting values, you'll need to store the results in a new array.

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]
    }
}
like image 181
martinez314 Avatar answered Jan 27 '26 12:01

martinez314



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!