1 divert(-1)dnl -*- m4 -*-
2 # Usage: m4 [-Dfile=day25.input] day25.m4
4 include(`common.m4')ifelse(common(25), `ok', `',
5 `errprint(`Missing common initialization
8 define(`input', translit((include(defn(`file'))), nl`,()', `;'))
10 define(`line', `_$0(translit(`$1', ` ', `,'))')
11 define(`_line', `define(`i'cnt, `$1')define(`a'cnt, quote(shift($@),
12 cnt))define(`cnt', incr(cnt))')
14 patsubst(defn(`input'), `\([^;]*\);', `line(`\1')')
16 define(`_chew', `line(substr(`$1', 0, index(`$1', `;')))define(`tail',
17 substr(`$1', incr(index(`$1', `;'))))ifelse(index(defn(`tail'), `;'), -1,
18 `', `$0(defn(`tail'))')')
19 define(`chew', `ifelse(eval($1 < 20), 1, `_$0(`$2')', `$0(eval($1/2),
20 substr(`$2', 0, eval($1/2)))$0(eval(len(defn(`tail')) + $1 - $1/2),
21 defn(`tail')substr(`$2', eval($1/2)))')')
22 chew(len(defn(`input')), defn(`input'))
25 define(`r_', `ifelse(len(`$1'), 1, `ifdef(`r$1', `r')')$1')
26 define(`cpy_', `define(`r$2', r_(`$1'))1')
27 define(`inc_', `define(`r$1', incr(r$1))1')
28 define(`dec_', `define(`r$1', decr(r$1))1')
29 define(`jnz_', `ifelse(`$1$2', 00, `hackhlt($3)', r_(`$1'), 0, 1, $2, -2,
30 `hackadd(`$1', `$2', decr(decr($3)), decr($3))', $2, -5, `hackmul(`$1',
31 `$2'forloop(eval($3 - 5), decr($3), `,'))', $2, -7, `hackdiv(`$1',
32 `$2'forloop(eval($3 - 7), decr($3), `,'))', `r_(`$2')')')
33 define(`hackadd', `ifelse(i$3.i$4, `dec.inc', `$0(`$1', `$2', $4, $3)',
34 i$3.i$4.first(a$4), `inc.dec.$1', `define(`r'first(a$3),
35 eval(defn(`r'first(a$3)) + r$1))define(`r$1', 0)1', `r_(`$2')')')
36 define(`hackmul', `ifelse(i$3.i$4.i$5.i$6.i$7, `cpy.inc.dec.jnz.dec',
37 `define(`r'first(a$4), eval(defn(`r'first(a$4)) + r_(first(a$3)) *
38 r$1))define(`r'first(a$5), 0)define(`r$1', 0)1', `r_(`$2')')')
39 define(`hackhlt', `_$0(`s$1_'ra`_'rb`_'rc`_'rd`_'o)')
40 define(`_hackhlt', `ifdef(`$1', `define(`done')cnt', `pushdef(`mod',
41 `$1')define(`$1')1')')
42 define(`hackdiv', `ifelse(i$3.i$4.i$5.i$6.i$7.i$8.i$9,
43 `cpy.jnz.jnz.dec.dec.jnz.inc', `define(`ra', eval(ra + rb / 2))define(`rc',
44 eval(2 - rb % 2))define(`rb', 0)1', `r_(`$2')')')
45 define(`out_', `ifelse(check(defn(`o'), r_(`$1')), -, 1, cnt)')
46 define(`check', `ifelse($1, $2, `', `define(`o', $2)-')')
47 define(`tgl_', `ifdef(`o', `errprintn(`mixing out and tgl is undefined')m4exit(
48 1)', `toggle(eval($2 + r_(`$1')))1')')
49 define(`toggle', `ifdef(`i$1', `pushdef(`mod', `i$1')pushdef(`i$1',
57 define(`run', `ifdef(`i$1', `$0(_$0(i$1, $1))')')
58 define(`_run', `eval($2 + $1_(a$2))')
59 define(`reset', `ifdef(`mod', `popdef(defn(`mod'))popdef(`mod')$0($1)',
60 `define(`ra', $1)define(`rb', 0)define(`rc', 0)define(`rd', 0)popdef(`o')')')
62 define(`do', `reset($1)run(0)ifdef(`done', `$1', `$0(incr($1))')')
63 define(`part1', do(0))