1 divert(-1)dnl -*- m4 -*-
2 # Usage: m4 [-Dfile=day15.input] day15.m4
4 include(`common.m4')ifelse(common(15), `ok', `',
5 `errprint(`Missing common initialization
8 # Translit to all caps to avoid macro collisions
9 # m4 lacks native byte->ASCII, so open-code it ;)
10 # Longest input string is 6 letters, =, then digit
12 define(`input', translit((include(defn(`file'))), defn(`alpha')nl`,()',
15 define(`part1', 0)define(`part2', 0)
16 define(`_ascii', `ifelse(`$2', `=', 61, `$2', `-', 45, `$1', -1, `$2+48',
18 define(`ascii', `_$0(index('dquote(defn(`ALPHA'))`, `$1'), `$1')')
19 define(`char', `eval(($1+$2)*17%256)')
20 define(`_add', `ifelse(`$1', `$2', `pushdef(`seen')')')
21 define(`add', `define(`v$2', `$3')_stack_foreach(`s$1', `_$0(', `, `$2')',
22 `t')ifdef(`seen', `popdef(`seen')', `pushdef(`s$1', `$2')')')
23 define(`_rem', `ifelse(`$1', `$3', `popdef(`s$2')')')
24 define(`rem', `define(`v$2', 0)_stack_foreach(`s$1', `_$0(', `, $@)', `t')')
25 define(`hash', `ifelse(`$3', `-', `rem($1, `$2')', `$3', `=', `add($1, `$2',
26 $4)')ifelse(`$3', `', `$1', `$0(char($1, ascii(`$3')), `$2$3',
27 shift(shift(shift($@))))')')
28 define(`do', `define(`part1', eval(part1 + translit(`hash(0, `', `1', `2', `3',
29 `4', `5', `6', `7', `8')', `12345678', `$1')))')
32 patsubst(defn(`input'), `\([^;]*\);', `do(`\1')')
34 define(`_chew', `do(substr(`$1', 0, index(`$1', `;')))define(
35 `tail', substr(`$1', incr(index(`$1', `;'))))ifelse(index(defn(`tail'),
36 `;'), -1, `', `$0(defn(`tail'))')')
37 define(`chew', `ifelse(eval($1 < 20), 1, `_$0(`$2')', `$0(eval($1/2),
38 substr(`$2', 0, eval($1/2)))$0(eval(len(defn(`tail')) + $1 - $1/2),
39 defn(`tail')substr(`$2', eval($1/2)))')')
40 chew(len(defn(`input')), defn(`input'))
43 define(`_power', `define(`part2', eval(part2+$2*$3*v$1))define(`i', incr($3))')
44 define(`power', `define(`i', 1)_stack_foreach(`s$1', `_$0(', `, 'incr($1)`, i)',
46 forloop_arg(0, 255, `power')
49 dnl For my reference, this is my golfed part 1, in POSIX...
50 define(C,`eval(($1+$2)*17%256)')define(B,`A(index(abcdefghijklmnopqrstuvwxyz,
51 $1),$1)')define(A,`ifelse($2,=,61,$2,-,45,$1,-1,$2+48,$1+97)')define(H,`ifelse(
52 $2,,$1,`H(C($1,B(substr($2,0,1))),substr($2,1))')')define(_,`+H(,$1)ifelse($2,,
53 ,`_(shift($@))')')eval(_(include(I)))
56 define(C,`eval(($1+$2)*17%256)')define(H,`ifelse($2,,$1,`H(C($1,
57 esyscmd(printf %d \"$2)),substr($2,1))')')define(_,`+H(,
58 $1)ifelse($2,,,`_(shift($@))')')eval(_(include(I)))