简体   繁体   中英

Shifting a 2D array in C#

I have a 2d array looking like this:

values = new int[11, 11] {
        { 00, 00, 00, 00, 00, 20, 20, 20, 20, 20, 20},
        { 00, 20, 20, 20, 00, 20, 20, 20, 20, 20, 20},
        { 00, 00, 20, 20, 00, 20, 20, 20, 20, 20, 20},
        { 20, 20, 20, 20, 00, 00, 00, 00, 00, 00, 20},
        { 20, 20, 20, 20, 20, 20, 20, 20, 20, 00, 20},
        { 20, 20, 20, 20, 20, 20, 20, 20, 20, 00, 20},
        { 20, 20, 20, 20, 20, 20, 00, 00, 00, 00, 20},
        { 20, 20, 20, 20, 20, 20, 00, 20, 20, 20, 20},
        { 20, 20, 20, 20, 20, 20, 00, 20, 20, 20, 20},
        { 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00},
        { 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00},
    };

Now I need to shift all layers by 1 down but all the rows need to stay the same. The layer at the bottom needs to be deleted and at the top a new layer needs to be created with all values 0. The result should look like this:

values = new int[11, 11] {
    { 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00},
    { 00, 00, 00, 00, 00, 20, 20, 20, 20, 20, 20},
    { 00, 20, 20, 20, 00, 20, 20, 20, 20, 20, 20},
    { 00, 00, 20, 20, 00, 20, 20, 20, 20, 20, 20},
    { 20, 20, 20, 20, 00, 00, 00, 00, 00, 00, 20},
    { 20, 20, 20, 20, 20, 20, 20, 20, 20, 00, 20},
    { 20, 20, 20, 20, 20, 20, 20, 20, 20, 00, 20},
    { 20, 20, 20, 20, 20, 20, 00, 00, 00, 00, 20},
    { 20, 20, 20, 20, 20, 20, 00, 20, 20, 20, 20},
    { 20, 20, 20, 20, 20, 20, 00, 20, 20, 20, 20},
    { 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00},
};

I tried to code a function using for loops to do this. But didn't succeed. This is one attempt for doing it:

for(int row = 11; row > 0; row--) {
    for(int col = 0; col < 11; col++) {
        targets[row, col] = targets[row + 1, col]; 
    }
}

Unfortunately this is the only attempt I still have. Can anyone please help me do this or has a finished function to do this?

Thanks for your time and help.

Just use Array.Copy , it will work with the contiguous memory of a multi-dimensional array

Copies a range of elements from an Array starting at the specified source index and pastes them to another Array starting at the specified destination index. The length and the indexes are specified as 64-bit integers.

Array.Copy(values,0, values,1, values.GetLength(0)* values.GetLength(1)-1);

Full Demo Here

Update

Sorry I used the wrong words. The layers need to be shifted one down but the rows must stay the same.

Then, you just need to do the math

Array.Copy(values,0, values, values.GetLength(0)+1, values.GetLength(0) * values.GetLength(1) -values.GetLength(0)-1);

// Zero out the first row
Array.Copy(new int[values.GetLength(0)+1,1],0,values , 0,values.GetLength(0)+1);

Full Demo Here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM