What is the fastest way to move simple data types in an array of known size to specific positions?
The specific case that I had was a rotation of the playing field stored as int [9]
[0,1,2,3,4,5,6,7,8] becomes [6,3,0,7,4,1,8,5,2]
In my use case, I had a vector of these arrays, each of which needed rotation.
Board Layout:
board1|corners|centers 0 1 2 | 0 2 | 1 3 4 5 | | 3 5 6 7 8 | 6 8 | 7 board2|corners|centers 6 3 0 | 6 0 | 3 7 4 1 | | 7 1 8 5 2 | 8 2 | 5
The fastest method I came across was to create a public variable for assigning array entries and then copy the memory back.
int layout[9]; int pub_layout[9]; #include <cstring> // for std::memcpy void rotate(int layout[]) { pub_layout[4] = layout[4]; // center pub_layout[0] = layout[6]; // corner four pub_layout[6] = layout[8]; pub_layout[8] = layout[2]; pub_layout[2] = layout[0]; pub_layout[1] = layout[3]; // center four pub_layout[3] = layout[7]; pub_layout[7] = layout[5]; pub_layout[5] = layout[1]; std::memcpy(layout,pub_layout,sizeof(pub_layout)); }
I saw a similar question here that recommends int[] b = new int[] {b[6], b[3], b[0], b[7], b[4], b[1], b[8], b[5], b[2]};
(although it works much slower (less than half the speed on a single thread)
Both are relatively fast ( see test here )
If this is not the fastest way, what is it? I suspect that the algorithm will be the same in both C and C ++.