# Complex permutation of elements of an array

This is a discussion on Complex permutation of elements of an array within the C Programming forums, part of the General Programming Boards category; I have written two rotation functions that operate on a character array of length equal to a perfect square. The ...

1. ## Complex permutation of elements of an array

I have written two rotation functions that operate on a character array of length equal to a perfect square.
The first rotate n times each odd line to the right and n times each pair line to the left. The second rotates n times each odd column down and n times each pair column up, where n is the numer of current line or column.

Example:
abcde
fghij
klmno
pqrst
uvwxy

Becomes:
eabcd
hijfg
mnokl
tpqrs
uvwxy

And finally:
unoxd
epqcg
hvwfl
mabks
tijry

I would like to reduce everything to a single function, or rather, to a single loop that moves each character in its final position without performing all the steps.
You can do this? Any suggestions?

2. In a 5x5 array, you will always have to process all 25 elements. Whether you do that in one loop of 25 iterations or nested loops of 5 iterations each, it amounts to the same thing. But the nested loops make more sense since the loop variables of each loop correspond exactly to the indexes in your 2-d array.

Instead of doing a literal rotation of each row and column, and shifting each letter individually each time, you can calculate the new coordinates and copy each letter into it's new location in a new array. Adding/subtracting n and doing a little modulus (%) work should get you there. Copy the new array back to the old one if need be. I don't know if it will be any faster, but you can implement both methods and measure them to see which is faster.

3. My problem is being able to immediately obtain the final position of each character. Can you post some code?

4. Nope. We don't hand out code here. I already gave you some big clues in my last post, adding/subtracting n, and using the modulus operator to wrap around. Per your description, you also need to know if it's an odd or even row/column, so you know whether it's shifting left or right, and up or down.

Work it out on paper for several values of n in your sample array. Once you understand how to do it on paper and can explain the steps, the code should come fairly easily.