How to flip rows in a 1D short/int array representing a 2D array in Java -


i need flip 1-d 64-element array of shorts (i can switch ints if it's easier, assume same processes work either) on it's head in java. represent here square table ease of understanding, since actual problem on chessboard.

for example:

short[] example = new short[] {     1, 2, 3,     4, 5, 6,     7, 8, 9 }; 

would become:

7 8 9 4 5 6 1 2 3 

please note not same reversing array (every answerer similar questions have found has made mistake, hence having ask!). reversing array give:

9 8 7 6 5 4 3 2 1 

apologies if i've missed important info, appreciated!

edit: array 1d , contains 64 elements, short[64], , reversed array separate original. far i've tried, i'm struggling wrap head around it. know how reverse array, that's not i'm after, , had tried reverse index using:

byte index = (byte)(((byte)(position + 56)) - (byte)((byte)(position / 8) * 16)); 

which code snippet found on chessbin, returns incorrect values , gives indexoutofbounds errors. in hindsight it's not clear me if code meant flip index or reverse it. since maths not strong suit, tried work around separate arrays.

you have physical 1d array representing logical 2d array, , want swap rows. can partly mapping 2d array indices 1d array index.

let height number of rows, , width number of columns.

for ( int = 0; < height/2; ++i ) {     int k = height - 1 - i;     ( int j = 0; j < width; ++j ) {         short temp = array[i * width + j];         array[i * width + j] = array[k * width + j];         array[k * width + j] = temp;     } }     

i've written readability. or compiler may optimize of repeated computations.

you might able optimize further using 2d array, allow swap references rows in o(height), rather copying rows in o(height * width).


Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -