Anymee
Anymee

Reputation: 121

How to rotate a section of a 1d array in C?

I printed out a 6x6 1d array but want to rotate counter-clockwise the top left 3x3 section. Is there an algorithm for this? In the future I also want to rotate like the bottom right 3x3 section or the top right 3x3 section or the bottom left 3x3 section.

a[0]  a[1]  a[2]  a[3]  a[4]  a[5]         a[1]  a[2]  a[8]  a[3]  a[4]  a[5]
a[6]  a[7]  a[8]  a[9]  a[10] a[11]        a[0]  a[7]  a[14] a[9]  a[10] a[11]
a[12] a[13] a[14] a[15] a[16] a[17]  --->  a[6]  a[12] a[13] a[18] a[19] a[20]
a[18] a[19] a[20] a[21] a[22] a[23]        a[18] a[19] a[20] a[21] a[22] a[23]
a[24] a[25] a[26] a[27] a[28] a[29]        a[24] a[25] a[26] a[27] a[28] a[29]
a[30] a[31] a[32] a[33] a[34] a[35]        a[30] a[31] a[32] a[33] a[34] a[35]

Upvotes: 2

Views: 475

Answers (1)

Lundin
Lundin

Reputation: 213832

Here it is important to distinguish between how things are allocated in memory and how you represent them. There is no such thing as a "6x6 1D array", because 1D arrays don't have rows and columns. So start by converting this 1D array to a 2D array 6x6.

You can then define a center for the rotation by specifying coordinates (x, y). You should sanity check these coordinates so that they are not at the edges of the matrix (alternatively, design the algorithm so that this is possible, if needed).


The blunt solution is to just grab the indices around the center and move data around in a hard-coded manner:

array[center_x-1][center_y-1] = array[center_x][center_y-1];
...

and so on. This will be the fastest way and the simplest solution is often the best one.


A more modular approach which allows for a variable rotating direction would be to create an array of pointers pointing at the data around the center that needs to be rotated. This array of pointers can be implemented as a simple form of linked list:

typedef struct rotate_node_t rotate_node_t;
typedef struct rotate_node_t
{
  rotate_node_t* next;
  rotate_node_t* prev;
  int* data;
} rotate_node_t;

You'd have a rotate_node_t rotation [8] which could have its indices assigned as:

0 1 2
7 c 3
6 5 4

where "c" is center.

With this in place, you can simply iterate through the linked list in any direction and move data from one node to the other. It is more flexible than direct array access, but slower and more complex. And it could be expanded to support all manner of wild rotation patterns.

Upvotes: 1

Related Questions