1 divert(-1)dnl -*- m4 -*-
2 # Usage: m4 [-Dfile=day07.input] day07.m4
4 include(`common.m4')ifelse(common(07), `ok', `',
5 `errprint(`Missing common initialization
8 define(`input', translit((include(defn(`file'))), nl`,()', `;;'))
9 define(`sum', 0)define(`count', 0)define(`min', 9999)define(`max', -1)
10 define(`visit', `define(`sum', eval(sum+$1))define(`count', incr(
11 count))ifdef(`v$1', `define(`v$1', incr(v$1))', `pushdef(`v', $1)define(
12 `v$1', 1)ifelse(eval($1 < min), 1, `define(`min', $1)')ifelse(eval($1 > max),
13 1, `define(`max', $1)')')')
15 patsubst(defn(`input'), `\([^;]*\);', `visit(`\1')')
17 define(`_chew', `visit(substr(`$1', 0, index(`$1', `;')))define(
18 `tail', substr(`$1', incr(index(`$1', `;'))))ifelse(index(defn(`tail'),
19 `;'), -1, `', `$0(defn(`tail'))')')
20 define(`chew', `ifelse(eval($1 < 10), 1, `_$0(`$2')', `$0(eval($1/2),
21 substr(`$2', 0, eval($1/2)))$0(eval(len(defn(`tail')) + $1 - $1/2),
22 defn(`tail')substr(`$2', eval($1/2)))')')
23 chew(len(defn(`input')), defn(`input'))
25 define(`score', `eval(_stack_foreach(`v', `dist($1, ', `)'))')
26 define(`dist', `+_$0(translit(eval($1 - $2), -))*v$2')
27 define(`search', `_$0($2($1), `$2', score($2($1)))')
28 define(`_search', `ifelse(eval($3 <= best), 1, `define(`best',
29 $3)search($1, `$2')')')
30 define(`find', `define(`best', score($1))search($1, `decr')search($1,
34 define(`try', `ifdef(`v$1', `ifdef(`med', `', `ifelse(eval(idx + v$1 >=
35 count / 2), 1, `define(`med', $1)', `define(`idx', eval(idx + v$1))')')')')
36 forloop_arg(min, max, `try')
38 define(`part1', find(med))
40 define(`_dist', `($1*($1+1)/2)')
41 define(`part2', find(eval(sum / count)))