I studied math, and I come up with this problem. There are two permutations A and B and a integer M. We say A almost equal to B if we can make from A to B doing following op
Here's a proof of my conjecture. Let n
be the length of the permutations and m
be the length of the windows that we are allowed to rotate, where 1 ≤ m ≤ n
. Permutations P
and Q
are almost equal if there exists a sequence of window rotations that transforms P
into Q
. Almost equality is an equivalence relation. Here's the claimed characterization of the equivalence classes.
(1) m = 1: P almost equals Q if and only if P = Q
(2) m = n: P almost equals Q if and only if they're rotations of each other
(3) 1 < m < n, m odd: P almost equals Q if and only if they have the same parity
(4) 1 < m < n, n even: P almost equals Q
The first two claims are obvious. As for (3)
, the necessity of the parity condition follows from the fact that rotating a window of odd length is an even permutation.
The meat of the argument here is to find an algorithm for when n = m + 1 ≥ 4
, since in general, we can use an algorithm similar to insertion sort to transform P
so that all but the last m + 1
elements match Q
, and specifically, the case (n, m) = (3, 2)
can be solved by inspection. In case m
is even, we ensure further that the transformation matches the parity of Q
, by rotating the last m
elements once if necessary. (For m
odd, we just assume equal parities.)
We need a technique for moving fewer than m
elements at once. Suppose that the state is as follows.
1, 2, 3, 4, ..., m, m + 1
Rotate the second window m - 1
times (i.e., once in reverse).
1, 3, 4, ..., m, m + 1, 2
Rotate the first window m - 1
times.
3, 4, ..., m, m + 1, 1, 2
Second, twice.
3, 2, 4, ..., m, m + 1, 1
3, 1, 2, 4, ..., m, m + 1
We've succeeded in rotating the first three elements. This suffices in combination with conjugation by rotations to "insertion sort" the first m - 1
elements of Q
into place. The other two are in the right order by the parity match.