interplane.Get Omega
Read in your language

omega-rosetta

aien-dev/omega-rosetta

Brought by drakestapleton

branch main Branches Tags History

omega-rosetta / tasks / knights-tour / oracle.py

21 lines · 1071 bytes Raw Blame History
1# Independent reference for "Knight's tour" (Python 3, standard library only).
2# expected.txt is this program's stdout; omc never produced it.
3moves = [(2, 1), (1, 2), (-1, 2), (-2, 1), (-2, -1), (-1, -2), (1, -2), (2, -1)]
4def onward(f, r, seen):
5 return [(f + dx, r + dy) for dx, dy in moves
6 if 0 <= f + dx < 8 and 0 <= r + dy < 8 and (f + dx, r + dy) not in seen]
7path = [(0, 0)]
8seen = {(0, 0)}
9while len(path) < 64:
10 cands = onward(*path[-1], seen)
11 assert cands, "Warnsdorff dead end"
12 nxt = min(cands, key=lambda s: len(onward(*s, seen))) # min keeps the first of equal keys
13 path.append(nxt)
14 seen.add(nxt)
15# the tour must be 64 distinct squares, each a knight's move from the one before
16assert len(set(path)) == 64
17assert all(sorted((abs(a[0] - b[0]), abs(a[1] - b[1]))) == [1, 2] for a, b in zip(path, path[1:]))
18num = {s: i + 1 for i, s in enumerate(path)}
19print("Warnsdorff tour from a1; each square shows its move number, rank 8 at the top")
20for r in range(7, -1, -1):
21 print("".join(f"{num[(f, r)]:3}" for f in range(8)))