1 divert(-1)dnl -*- m4 -*-
2 # Usage: m4 [-Dfile=day7.input] day7.m4
4 include(`intcode.m4')ifelse(intcode(7), `ok', `',
5 `errprint(`Missing IntCode initialization
11 # Feed id to each machine, stop after input
12 define(`prep', `pushdef(`io', defn(`pause_after_read'))
13 oneshot(`read', $1)copy(`a')runs(`a')
14 oneshot(`read', $2)copy(`b')runs(`b')
15 oneshot(`read', $3)copy(`c')runs(`c')
16 oneshot(`read', $4)copy(`d')runs(`d')
17 oneshot(`read', $5)copy(`e')runs(`e')
18 define(`data', 0)popdef(`io')')
20 # Loop until E calls done, expect read then write, then pause before any read
21 # (expectations are a stack, create them in reverse order)
22 define(`write', `define(`data', $1)')
23 define(`read', `data')
24 define(`done', `define(`repeat')')
26 oneshot(`io', defn(`pause_after_write'))
27 oneshot(`io', defn(`run_after_read'))
29 oneshot(`io', defn(`pause_after_write'))
30 oneshot(`io', defn(`run_after_read'))
32 oneshot(`io', defn(`pause_after_write'))
33 oneshot(`io', defn(`run_after_read'))
35 oneshot(`io', defn(`pause_after_write'))
36 oneshot(`io', defn(`run_after_read'))
38 oneshot(`io', defn(`pause_on_read'))
39 oneshot(`io', defn(`run_after_write'))
40 oneshot(`io', defn(`run_after_read'))
44 define(`try', `prep(substr($1, 0, 1), substr($1, 1, 1), substr($1, 2, 1),
45 substr($1, 3, 1), substr($1, 4, 1))define(`repeat', `loop()')loop()
46 ifelse(eval(data > best), 1, `define(`best', data)')')
48 define(`swap', `define(`str',
49 substr(str, 0, $1)substr(str, $2, 1)substr(str, incr($1),
50 eval($2 - $1 - 1))substr(str, $1, 1)substr(str, incr($2)))str')
51 define(`permute', `pushdef(`str', $1)_$0($1, len($1))popdef(`str')')
52 define(`_permute', `ifelse($2, 1, `try($1)',
53 `$0($1, decr($2))forloop_var(`x', 0, decr(decr($2)),
54 `$0(swap(ifelse(eval($2 & 1), 1, 0, x), decr($2)), decr($2))')')')