1 divert(-1)dnl -*- m4 -*-
2 # Usage: m4 [-Dfile=day8.input] day8.m4
4 include(`common.m4')ifelse(common(8), `ok', `',
5 `errprint(`Missing common initialization
8 define(`input', translit(include(defn(`file')), nl` ', `;;'))
10 define(`nodes', 1)define(`children', 1)
11 define(`rdmeta', `define(`part1', eval(part1 + $1))ifelse(children, 0,
12 `define(`sum', eval(sum + $1))', $1, 0, `', eval($1 > children), 1, `',
13 `define(`sum', eval(sum + c$1))')define(`meta', decr(meta))')
14 define(`rdhead', `ifdef(`n', `define(`nodes', decr(nodes))pushdef(`nodes',
15 n)pushdef(`children', n)pushdef(`meta', $1)pushdef(`sum', 0)popdef(`n')',
17 define(`clean', `ifelse(children, 0, `', `forloop(1, children, `popdef(`c'',
18 `)')')popdef(`children')popdef(`nodes')popdef(`meta')pushdef(`c'eval(
19 children - nodes), sum)popdef(`sum')')
20 define(`visit', `ifelse(nodes, 0, `rdmeta', `rdhead')(`$1')ifelse(nodes`'meta,
23 patsubst(defn(`input'), `\([^;]*\);', `visit(`\1')')
25 define(`_chew', `visit(substr(`$1', 0, index(`$1', `;')))define(`tail',
26 substr(`$1', incr(index(`$1', `;'))))ifelse(index(defn(`tail'), `;'), -1,
27 `', `$0(defn(`tail'))')')
28 define(`chew', `ifelse(eval(`$1 < 6'), 1, `_$0(`$2')', `$0(eval(`$1/2'),
29 substr(`$2', 0, eval(`$1/2')))$0(eval(len(defn(`tail'))` + $1 - $1/2'),
30 defn(`tail')substr(`$2', eval(`$1/2')))')')
31 chew(len(defn(`input')), defn(`input'))