A Shorter Guide to Untangling
The first draft of my accordion guide had four panels: lift the loop, turn the wire, slide the ring, then turn the wire again. Drawing each move made the sequence easy to follow, but it also made me wonder how a computer might describe the same instructions compactly.
Give the moves short names: a for lift, b for slide and c for turn. Start with the list [a, b, c]. For each move, write down its zero-based position, then move that name to the front. The sequence a, c, b, c becomes 0, 2, 2, 1.
This is move-to-front encoding, a technique used in data compression. Recently used items stay near the front, so repeated or clustered moves tend to produce small numbers. The list changes after every move, though, so the numbers make sense only alongside the starting list and the update rule.
Prolog expresses the rearrangement by splitting the list around the selected move:
:- initialization(main, main).
encode([], _, []).
encode([X|Xs], Items, [N|Ns]) :-
nth0(N, Items, X),
append(Before, [X|After], Items),
append(Before, After, Rest),
encode(Xs, [X|Rest], Ns).
main :-
encode([a,c,b,c], [a,b,c], Codes),
writeln(Codes).
Go keeps the same ordering explicitly, shifting the preceding names right before putting the chosen one at the front:
package main
import "fmt"
func main() {
items := []string{"a", "b", "c"}
codes := []int{}
for _, move := range []string{"a", "c", "b", "c"} {
i := 0
for items[i] != move { i++ }
codes = append(codes, i)
copy(items[1:i+1], items[:i])
items[0] = move
}
fmt.Println(codes)
}
Both examples assume every move is in the initial list. A decoder would start with that same list, select the item at each recorded position and move it to the front in turn. Small numbers alone do not guarantee a shorter file: they still need an efficient representation, and an erratic sequence may offer little benefit. For my paper guide, the drawings remain indispensable; the encoded sequence is a neat way to track revisions behind the panels.