Public: anyone can read this; the crew can change it.

Migrated from github.com/amirmushichge/pixel-plays

Shunting Yard rules: a tested `shunting-yard/yard.js` that sorts numbered wagons through sidings from plain data #171

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

torque/pixel-plays:torque/162-shunting-yard-rules-a-tested-shunting-ya → main 1 commit fork

  • Merged. torque/162-shunting-yard-rules-a-tested-shunting-ya was merged into main as 0ac2869.

Review

Sign in to review this change.
2 files changed +267 −0
shunting-yard/yard.js added +130
@@ -0,0 +1,130 @@
1 'use strict';
2 // The Shunting Yard rules: a mixed-up train of numbered wagons on the arrival track, a few short sidings, and an empty
3 // departure track the wagons must reach in order 1, 2, 3... in as few moves as you can.
4 // Plain data in, plain data out, no DOM, no timers, no Math.random: the shuffle comes from the seed. A refused move
5 // returns the very same state and says why. The page draws what this decides.
6 //
7 // Tracks are an array: tracks[0] is the arrival track, tracks[1..SIDINGS] the sidings, the last the departure track.
8 // Each track lists its wagons from the buffer stop outward, so the end wagon (the one that can move) is the last item.
9 (function (root) {
10 const SIDINGS = 2, CAPACITY = 3; // sidings in the yard, and the wagons each holds
11 const FIRST_WAGONS = 3, LAST_LEVEL = 5; // level L has FIRST_WAGONS + L - 1 wagons; the game ends after LAST_LEVEL
12 const DEPARTURE = SIDINGS + 1; // index of the departure track
13 const TARGETS = { 1: 5, 2: 7, 3: 9, 4: 11, 5: 13 }; // moves per level that still win (every level's yard solves within its target)
14
15 const finite = v => (Number.isFinite(v) ? v : 0);
16 // a repeatable number in [0, 1) for this seed and slot
17 function noise(seed, n) {
18 let h = (Math.imul(finite(seed) | 0, 374761393) + Math.imul(n | 0, 668265263)) | 0;
19 h = Math.imul(h ^ (h >>> 13), 1274126177);
20 return ((h ^ (h >>> 16)) >>> 0) / 4294967296;
21 }
22 const clampLevel = l => Math.min(LAST_LEVEL, Math.max(1, Math.floor(finite(l)) || 1));
23 const wagonsAt = level => FIRST_WAGONS + clampLevel(level) - 1;
24 const target = level => TARGETS[clampLevel(level)];
25 const copyTracks = t => t.map(w => w.slice());
26 const keyOf = tracks => tracks.map(w => w.join(',')).join('|');
27
28 // why a wagon may not go from track `from` to track `to` on these tracks, or '' when it may
29 function refusal(tracks, from, to) {
30 if (!Number.isInteger(from) || !Number.isInteger(to) || from < 0 || to < 0 || from > DEPARTURE || to > DEPARTURE) return 'no-such-track';
31 if (from === to) return 'same-track';
32 if (from === DEPARTURE) return 'departed'; // a wagon on the departure track has left
33 if (to === 0) return 'arrival-closed'; // nothing is shunted back onto the arrival track
34 if (!tracks[from].length) return 'empty-track';
35 const wagon = tracks[from][tracks[from].length - 1];
36 if (to === DEPARTURE) return wagon === tracks[DEPARTURE].length + 1 ? '' : 'out-of-order';
37 return tracks[to].length >= CAPACITY ? 'siding-full' : '';
38 }
39 const moves = tracks => {
40 const out = [];
41 for (let f = 0; f < DEPARTURE; f++) for (let t = 1; t <= DEPARTURE; t++) if (!refusal(tracks, f, t)) out.push([f, t]);
42 return out;
43 };
44 const sorted = tracks => tracks[DEPARTURE].length === tracks.reduce((n, w) => n + w.length, 0);
45
46 // Breadth-first search for the fewest moves that bring every wagon to the departure track: a list of [from, to], or null.
47 function solve(tracks, limit = 40) {
48 if (tracks && tracks.tracks) tracks = tracks.tracks;
49 const start = copyTracks(tracks);
50 let frontier = [{ tracks: start, path: [] }];
51 const seen = new Set([keyOf(start)]);
52 for (let d = 0; d <= limit && frontier.length; d++) {
53 const next = [];
54 for (const node of frontier) {
55 if (sorted(node.tracks)) return node.path;
56 for (const [f, t] of moves(node.tracks)) {
57 const nt = copyTracks(node.tracks);
58 nt[t].push(nt[f].pop());
59 const k = keyOf(nt);
60 if (!seen.has(k)) { seen.add(k); next.push({ tracks: nt, path: node.path.concat([[f, t]]) }); }
61 }
62 }
63 frontier = next;
64 }
65 return null;
66 }
67
68 // The yard for a seed and level: the wagons shuffled (Fisher-Yates on the seed's noise) onto the arrival track. A shuffle
69 // is kept only when it solves within the level's target, so every yard it makes can be won.
70 function layout(seed, level) {
71 const n = wagonsAt(level);
72 for (let attempt = 0; ; attempt++) {
73 const train = Array.from({ length: n }, (_, i) => i + 1);
74 for (let i = n - 1; i > 0; i--) {
75 const j = Math.floor(noise(seed, attempt * 64 + i) * (i + 1));
76 [train[i], train[j]] = [train[j], train[i]];
77 }
78 const tracks = [train, ...Array.from({ length: SIDINGS }, () => []), []];
79 const path = solve(tracks, target(level));
80 if (path && path.length > 0) return tracks;
81 }
82 }
83
84 const report = s => {
85 const against = `target ${s.targetTotal}`;
86 s.line = s.status === 'won' ? `Won: ${s.cleared} levels cleared in ${s.moves} moves (${against})`
87 : s.status === 'lost' ? `Lost: ${s.cleared} levels cleared in ${s.moves} moves, over ${against}`
88 : `Level ${s.level} of ${LAST_LEVEL}: ${s.moves} moves, ${s.levelMoves} of ${target(s.level)} on this level`;
89 return s;
90 };
91
92 // A new game at a level (1 by default) from a seed. moves counts every accepted move; levelMoves those on this level.
93 function start(seed = 1, level = 1) {
94 seed = finite(seed) >>> 0; level = clampLevel(level);
95 return report({
96 seed, level, tracks: layout(seed, level), wagons: wagonsAt(level), moves: 0, levelMoves: 0,
97 cleared: level - 1, targetTotal: sumTargets(level - 1), status: 'playing', reason: '', line: '',
98 });
99 }
100 const sumTargets = n => { let t = 0; for (let l = 1; l <= n; l++) t += target(l); return t; };
101
102 // Take the end wagon of track `from` to the end of track `to`. Returns { state, ok, why, events }; on refusal state is the
103 // same object, unchanged. Solving a level starts the next one (one more wagon); solving the last ends the game.
104 function move(s, from, to) {
105 const refuse = why => ({ state: s, ok: false, why, events: [] });
106 if (s.status !== 'playing') return refuse('game-over');
107 const why = refusal(s.tracks, from, to);
108 if (why) return refuse(why);
109 const tracks = copyTracks(s.tracks), wagon = tracks[from].pop();
110 tracks[to].push(wagon);
111 const events = [{ type: 'move', wagon, from, to }];
112 let n = Object.assign({}, s, { tracks, moves: s.moves + 1, levelMoves: s.levelMoves + 1 });
113 if (sorted(tracks)) {
114 n.cleared = s.level; n.targetTotal = sumTargets(s.level);
115 events.push({ type: 'cleared', level: s.level, moves: n.levelMoves });
116 if (s.level >= LAST_LEVEL) {
117 n.status = n.moves <= n.targetTotal ? 'won' : 'lost';
118 events.push({ type: n.status, cleared: n.cleared, moves: n.moves, target: n.targetTotal });
119 } else {
120 n.level = s.level + 1; n.wagons = wagonsAt(n.level); n.levelMoves = 0;
121 n.tracks = layout(s.seed + s.level, n.level); // each level has its own shuffle, still fixed by the seed
122 events.push({ type: 'level', level: n.level });
123 }
124 }
125 return { state: report(n), ok: true, why: '', events };
126 }
127
128 const api = { SIDINGS, CAPACITY, DEPARTURE, FIRST_WAGONS, LAST_LEVEL, TARGETS, start, move, solve, target, wagonsAt };
129 if (typeof module !== 'undefined') module.exports = api; else root.ShuntingYard = api;
130 })(typeof window !== 'undefined' ? window : globalThis);
shunting-yard/yard.test.mjs added +137
@@ -0,0 +1,137 @@
1 import { test, expect } from 'bun:test';
2 import { SIDINGS, CAPACITY, DEPARTURE, LAST_LEVEL, TARGETS, start, move, solve, target, wagonsAt } from './yard.js';
3
4 const play = (s, path) => path.reduce((st, [f, t]) => { const r = move(st, f, t); expect([f, t, r.why]).toEqual([f, t, '']); return r.state; }, s);
5 const yard = (tracks, extra = {}) => Object.assign(start(1, 1), { tracks }, extra);
6
7 test('a yard has an arrival track, the stated sidings and an empty departure track, with the wagons shuffled onto arrival', () => {
8 for (let level = 1; level <= LAST_LEVEL; level++) {
9 const s = start(7, level);
10 expect(s.tracks).toHaveLength(SIDINGS + 2);
11 expect(s.tracks[0].slice().sort((a, b) => a - b)).toEqual(Array.from({ length: wagonsAt(level) }, (_, i) => i + 1));
12 expect(wagonsAt(level)).toBe(3 + level - 1);
13 for (let i = 1; i <= SIDINGS; i++) expect(s.tracks[i]).toEqual([]);
14 expect(s.tracks[DEPARTURE]).toEqual([]);
15 expect(s.moves).toBe(0);
16 expect(s.status).toBe('playing');
17 }
18 });
19
20 test('the same seed and level always give the same yard, and seeds differ', () => {
21 expect(start(42, 4)).toEqual(start(42, 4));
22 const trains = new Set(Array.from({ length: 20 }, (_, i) => start(i, 5).tracks[0].join()));
23 expect(trains.size).toBeGreaterThan(5);
24 });
25
26 test('a solver reaches the departure track for every level and many seeds, within the level target', () => {
27 for (let level = 1; level <= LAST_LEVEL; level++) {
28 for (let seed = 0; seed < 8; seed++) {
29 const s = start(seed, level), path = solve(s);
30 expect(path).not.toBeNull();
31 expect(path.length).toBeLessThanOrEqual(target(level));
32 let st = s;
33 for (const [f, t] of path) {
34 const r = move(st, f, t);
35 expect(r.ok).toBe(true);
36 st = r.state;
37 if (st.level !== level) break; // solved: the next level took over
38 }
39 expect(st.cleared).toBeGreaterThanOrEqual(level);
40 }
41 }
42 });
43
44 test('a move from an empty track is refused and the state is the same object', () => {
45 const s = start(1, 1);
46 const r = move(s, 1, 2);
47 expect(r.ok).toBe(false);
48 expect(r.why).toBe('empty-track');
49 expect(r.state).toBe(s);
50 expect(s.moves).toBe(0);
51 });
52
53 test('a move onto a full siding is refused', () => {
54 const s = yard([[5, 4], [1, 2, 3], [], []], { wagons: 5 });
55 const r = move(s, 0, 1);
56 expect(r.why).toBe('siding-full');
57 expect(r.state).toBe(s);
58 expect(CAPACITY).toBe(3);
59 });
60
61 test('a move onto the departure track out of number order is refused, and in order accepted', () => {
62 const s = yard([[1, 3, 2], [], [], []]);
63 expect(move(s, 0, DEPARTURE).why).toBe('out-of-order'); // 2 is not next: 1 is
64 const t = yard([[3, 2, 1], [], [], []]);
65 expect(move(t, 0, DEPARTURE).ok).toBe(true);
66 });
67
68 test('other refusals: no such track, same track, leaving departure, back onto arrival, after the game', () => {
69 const s = yard([[3, 2], [1], [], []]);
70 expect(move(s, 0, 9).why).toBe('no-such-track');
71 expect(move(s, 'a', 1).why).toBe('no-such-track');
72 expect(move(s, 1, 1).why).toBe('same-track');
73 expect(move(s, 1, 0).why).toBe('arrival-closed');
74 expect(move(yard([[], [], [], [1]]), DEPARTURE, 1).why).toBe('departed');
75 expect(move(yard([[3, 2, 1], [], [], []], { status: 'won' }), 0, 1).why).toBe('game-over');
76 });
77
78 test('each accepted move counts one and a refused move counts none', () => {
79 let s = yard([[2, 1], [], [], []]);
80 s = move(s, 0, 1).state;
81 expect(s.moves).toBe(1);
82 expect(move(s, 2, 3).ok).toBe(false);
83 expect(s.moves).toBe(1);
84 s = move(s, 0, 2).state;
85 expect([s.moves, s.levelMoves]).toEqual([2, 2]);
86 expect(s.tracks).toEqual([[], [1], [2], []]);
87 });
88
89 test('solving a level starts the next with one more wagon and keeps the move count', () => {
90 const s = start(3, 1);
91 const path = solve(s);
92 const done = play(s, path);
93 expect(done.level).toBe(2);
94 expect(done.cleared).toBe(1);
95 expect(done.wagons).toBe(4);
96 expect(done.tracks[0]).toHaveLength(4);
97 expect(done.tracks[DEPARTURE]).toEqual([]);
98 expect(done.moves).toBe(path.length);
99 expect(done.levelMoves).toBe(0);
100 expect(done.status).toBe('playing');
101 });
102
103 function playAll(seed, waste = 0) {
104 let s = start(seed, 1);
105 while (s.status === 'playing') {
106 if (waste > 0 && s.levelMoves === 0 && s.level === 1) { // shuffle a wagon out and back, two moves each time
107 for (let i = 0; i < waste; i++) { s = move(s, 0, 1).state; s = move(s, 1, 2).state; s = move(s, 2, 1).state; }
108 }
109 const r = move(s, ...solve(s)[0]);
110 expect(r.ok).toBe(true);
111 s = r.state;
112 }
113 return s;
114 }
115
116 test('clearing the last level at or under the targets is a win and reports levels and moves', () => {
117 const s = playAll(5);
118 expect(s.status).toBe('won');
119 expect(s.cleared).toBe(LAST_LEVEL);
120 expect(s.moves).toBeLessThanOrEqual(Object.values(TARGETS).reduce((a, b) => a + b));
121 expect(s.line).toBe(`Won: ${LAST_LEVEL} levels cleared in ${s.moves} moves (target ${s.targetTotal})`);
122 expect(move(s, 0, 1).why).toBe('game-over');
123 });
124
125 test('clearing the last level over the targets is a loss and says so', () => {
126 const s = playAll(5, 6);
127 expect(s.moves).toBeGreaterThan(s.targetTotal);
128 expect(s.status).toBe('lost');
129 expect(s.cleared).toBe(LAST_LEVEL);
130 expect(s.line).toBe(`Lost: ${LAST_LEVEL} levels cleared in ${s.moves} moves, over target ${s.targetTotal}`);
131 });
132
133 test('inputs out of range are clamped, not trusted', () => {
134 expect(start(NaN, 99).level).toBe(LAST_LEVEL);
135 expect(start(1, -3).level).toBe(1);
136 expect(start(1.5, 2.9).level).toBe(2);
137 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs