1 divert(-1)dnl -*- m4 -*-
2 # Usage: m4 [-Dfile=day21.input] day21.m4
4 include(`common.m4')ifelse(common(21), `ok', `',
5 `errprint(`Missing common initialization
8 define(`input', translit(include(defn(`file')), nl`.#/ =>', `;01'))
9 define(`c2', 0)define(`c3', 0)
10 define(`line', `ifelse(len(`$1'), 13, `line2(substr(`$1', 0, 4), substr(`$1',
11 4))', `line3(substr(`$1', 0, 9), substr(`$1', 9))')')
12 define(`line2', `define(`r2'c2, `$2')_$0(3, `$1', c2)define(`c2', incr(c2))')
13 define(`_line2', `define(`p2$2', `$3')ifelse(`$1', 0, `', `$0(decr($1),
15 define(`rot', `translit(`3142', `1234', `$1')')
16 define(`line3', `define(`r3'c3, `$2')define(`l'c3, len(translit(`$1',
17 0)))_$0t(3, `$1', c3)define(`c3', incr(c3))')
18 define(`_line3t', `define(`p3$2', `$3')_line3s($1, tran(`$2'), `$3')')
19 define(`_line3s', `define(`p3$2', `$3')ifelse(`$1', 0, `', `_line3t(decr(`$1'),
21 define(`tran', `translit(`147258369', `123456789', `$1')')
22 define(`swap', `translit(`789456123', `123456789', `$1')')
24 patsubst(defn(`input'), `\([^;]*\);', `line(`\1')')
26 define(`chew', `line(substr(`$1', 0, index(`$1', `;')))define(`tail',
27 substr(`$1', incr(index(`$1', `;'))))ifelse(index(defn(`tail'), `;'),
28 -1, `', `$0(defn(`tail'))')')
29 define(`split', `ifelse(eval($1 < 70), 1, `chew(`$2')', `$0(eval($1/2),
30 substr(`$2', 0, eval($1/2)))$0(eval(len(defn(`tail')) + $1 - $1/2),
31 defn(`tail')substr(`$2', eval($1/2)))')')
32 split(len(defn(`input')), defn(`input'))
35 define(`init', p3010001111)
36 pushdef(`q0', init)define(`c0_'init, 1)
37 define(`iter', `_$0(decr($1), $1)')
38 define(`_iter', `ifdef(`q$1', `bump(q$1, $1, $2)popdef(`q$1')$0($@)')')
39 define(`expand2', `first(translit(
40 ``r2'p2ABEF`()r2'p2CDGH`()r2'p2IJMN`()r2'p2KLOP', `ABCDEFGHIJKLMNOP',
42 define(`do', ``,'defn(`p3'r2$1)')
43 define(`expand', `define(`L$1', translit(`do(p2ABDE)do(p2CJFM)do(p2KLNO)''dnl
44 ``do(p2GHST)do(p2IPU1)do(p2QR_3)do(p2VWYZ)do(p2X407)do(p25689)',
45 `ABCDEFGHIJKLMNOPQRSTUVWXYZ01_3456789', expand2(`$1')))')
46 define(`bump', `ifdef(`L$1', `', `expand(`$1')')_foreach(`_$0(c$2_$1, $3, ',
47 `)', L$1)popdef(`c$2_$1')')
48 define(`_bump', `ifdef(`c$2_$3', `define(`c$2_$3', eval(c$2_$3 + $1))',
49 `pushdef(`q$2', $3)define(`c$2_$3', $1)')')
50 define(`lit2', `len(translit(expand2(`$1'), 0))')
52 define(`_tally', `+c$1_$2*lit$3(`$2')')
53 define(`tally', `eval(0_stack_foreach(`q$1', `_$0($1, ', `, `$2')', `t'))')
55 define(`part1', tally(1, 2))
56 forloop_arg(2, 6, `iter')
57 define(`part2', tally(6, 0))