1 divert(-1)dnl -*- m4 -*-
2 # Usage: m4 [-Dfile=day5.input] day5.m4
4 include(`common.m4')ifelse(common(5), `ok', `',
5 `errprint(`Missing common initialization
8 # Careful: no one letter macro names, and append _ after any substr of the
9 # input more than length 1 to be sure there is no inadvertent macro expansion
10 define(`prep', `_$0(substr(alpha, $1, 1), substr(ALPHA, $1, 1))')
11 define(`_prep', `define(`p$1', `$2')define(`p$2', `$1')')
12 forloop_arg(0, 25, `prep')
14 define(`input', translit(include(defn(`file')), nl))
15 define(`visit', `ifelse(stack0, p$1, `popdef(`stack0')define(`part1',
16 decr(part1))', `pushdef(`stack0', `$1')define(`part1', incr(part1))')')
18 patsubst(defn(`input'), `.', `visit(`\&')')
20 define(`chew', `ifelse($1, 1, `visit(substr(`$2',0, 1))', `$0(eval($1/2),
21 substr(`$2', 0, eval($1/2))_)$0(eval($1 - $1/2), substr(`$2',
23 chew(len(defn(`input')), defn(`input')_)
26 define(`part2', part1)
27 define(`filter', `define(`sum', 0)_$0(`$1', substr(alpha, `$1', 1))ifelse(
28 eval(sum < part2), 1, `define(`part2', sum)')')
29 define(`_filter', `$0_(`$1', incr(`$1'), `$2', p$2, stack$1)')
30 define(`_filter_', `ifdef(`stack$1', `pushdef(`stack$2', `$5')ifelse(`$5',
31 `$3', `', `$5', `$4', `', p$5, stack$3, `popdef(`stack$3')define(`sum',
32 decr(sum))', `pushdef(`stack$3', `$5')define(`sum', incr(sum))')popdef(
33 `stack$1')$0(`$1', `$2', `$3', `$4', stack$1)')')
34 forloop_arg(0, 25, `filter')