The Swap a Puzzle Won't Allow
A puzzle on my shelf has three labelled pieces. Its mechanism moves them three at a time: the first takes the second’s place, the second takes the third’s, and the third takes the first’s. That sounds generous enough, until someone asks for just two pieces to trade places.
The obstruction is permutation parity. Put the pieces in their intended order, then count the pairs that appear backwards. Each backwards pair is an inversion. An even count means an even permutation; an odd count means an odd one.
This JavaScript checks a few arrangements. The labels are distinct numbers, and ascending order is the solved arrangement:
function parity(pieces) {
let inversions = 0;
for (let i = 0; i < pieces.length; i++) {
for (let j = i + 1; j < pieces.length; j++) {
if (pieces[i] > pieces[j]) inversions++;
}
}
return inversions % 2 === 0 ? "even" : "odd";
}
for (const pieces of [[1, 2, 3], [2, 3, 1], [2, 1, 3]]) {
console.log(pieces.join(" "), parity(pieces));
}
The first two arrangements are even; the last is odd. A three-piece cycle is equivalent to two swaps, so it preserves parity. Starting from the solved arrangement, any sequence of those moves stays even. A lone swap is odd and therefore cannot be reached by that mechanism alone.
Erlang can express the same count as a list of inverted pairs. Save this as parity.erl, then run erlc parity.erl and erl -noshell -s parity main -s init stop:
-module(parity).
-export([main/0]).
parity(Pieces) ->
Indexed = lists:zip(lists:seq(1, length(Pieces)), Pieces),
Inversions = [{A, B} || {I, A} <- Indexed, {J, B} <- Indexed,
I < J, A > B],
case length(Inversions) rem 2 of 0 -> even; 1 -> odd end.
main() ->
[io:format("~p ~p~n", [P, parity(P)]) ||
P <- [[1, 2, 3], [2, 3, 1], [2, 1, 3]]].
Both versions inspect every pair, which is perfectly comfortable for three pieces but grows quadratically with collection size. Parity also gives only a necessary condition here: an even arrangement is not automatically reachable in every puzzle. Still, it is a useful collector’s clue when a supposedly scrambled mechanism has been taken apart and reassembled.