I have an array such as
A-B-C-D-E-F-G-H-I-J-K
I want to rotate it N places to the right; for example, if N=3, the array should end
I-J-K-A-B-C-D-E-F-G-H
Assume that the only available operation is a FLIP method that can invert any portion of the array. For example, applied to the original array FLIP(3,6) would produce A-B-F-E-D-C-G-H-I-J-K.
It seems the solution does not work for array of lenth 5 and rotate to 3 places
L-5 N-3
ABCDE
FLIP(1,L-N) -> FLIP(1,2) -> BACDE
FLIP(L-N+1,N) -> FLIP(5-3+1,3) -> FLIP(3,3)->BACDE
FLIP(1,N) -> FLIP(1,3)->DACBE
Whereas the expected result is CDEAB
I suggest the below one:
fromPos=1; toPos=(N+1)%L;
if(fromPos == toPos) return;
for(numFlips=1;numFlips<=L;numFlips++){
flip(fromPos, toPos);
toPos=(toPos+N)%L;
if(fromPos == toPos) fromPos++;
}
|
Posted by sundaram
on 2006-12-03 08:04:28 |