1 divert(-1)dnl -*- m4 -*-
2 # Usage: m4 [-Dfile=day1.input] day1.m4
4 include(`common.m4')ifelse(common(1), `ok', `',
5 `errprint(`Missing common initialization
8 define(`input', include(defn(`file')))
9 define(`part1', eval(input))
10 ifelse(eval(part1 <= 0), 1, `errprintn(`corner case not handled')m4exit(1)')
11 define(`offset', `100000')define(`s', 0)define(`c', 0)
12 define(`line', `_$0(eval(s` + $1'), c)define(`c', incr(c))')
13 define(`_line', `define(`s', `$1')mark(eval(($1+'offset`)%'part1`), `$1', `$2')')
14 define(`mark', `ifdef(`l$1', `', `pushdef(`list', `$1')')pushdef(`l$1',
17 patsubst(translit(defn(`input'), nl, `;'), `\([^;]*\);', `line(`\1')')
19 define(`_chew', `line(substr(`$1', 0, index(`$1', `;')))define(`tail',
20 substr(`$1', incr(index(`$1', `;'))))ifelse(index(defn(`tail'),
21 `;'), -1, `', `$0(defn(`tail'))')')
22 define(`chew', `ifelse(eval(`$1 < 15'), 1, `_$0(`$2')', `$0(eval(`$1/2'),
23 substr(`$2', 0, eval(`$1/2')))$0(eval(len(defn(`tail'))` + $1 - $1/2'),
24 defn(`tail')substr(`$2', eval(`$1/2')))')')
25 chew(len(defn(`input')), translit(defn(`input'), nl, `;'))
27 define(`diff', 999999)define(`idx', c)
28 define(`pair', `ifelse(`$3', `', `', `_$0($@)$0(`$1', shift(shift($@)))')')
29 define(`_pair', `ifelse(`$3', `', `', `$1($2, $3)$0(`$1', `$2',
30 shift(shift(shift($@))))')')
31 define(`use', `ifdef(`$1', `,defn(`$1')popdef(`$1')$0(`$1')')')
32 define(`do', `pair(`_$0'use(`l$1'))')
33 define(`_do', `$0_(ifelse(eval(`$1>$3'), 1, ``($1 - $3)',`$4',`$1'',
34 ``($3 - $1)',`$2',`$3''), diff, idx)')
35 define(`_do_', `ifelse(eval(`$1<$4||($1==$4&&$2<$5)'), 1, `define(`diff',
36 eval(`$1'))define(`idx', `$2')define(`part2', `$3')')')
37 define(`loop', `ifdef(`list', `do(list)popdef(`list')$0()')')