1 divert(-1)dnl -*- m4 -*-
2 # Usage: m4 [-Dfile=day2.input] day2.m4
4 include(`common.m4')ifelse(common(2), `ok', `',
5 `errprint(`Missing common initialization
8 define(`input', translit(include(defn(`file')), nl` ', `; '))
9 define(`part1', 0)define(`part2', 0)
10 define(`store', `define(`a'n, $1)define(`n', incr(n))')
11 define(`find', `define(`part2', eval(part2 + forloop_arg(0, decr($1), `_$0')))')
12 define(`_find', `forloop(incr($1), decr(n), `pair($1,', `)')')
13 define(`pair', `ifelse(eval(a$1%a$2), 0, `a$1/a$2', eval(a$2%a$1), 0,
15 define(`line', `define(`n', 0)_$0(, translit(`$1', ` ', `,'))find(decr(n))')
16 define(`_line', `ifelse($1, `', `store($2)$0($2$@)', $3, `', `define(`part1',
17 eval(part1 + $2 - $1))', `store($3)$0(ifelse(eval($3 < $1), 1, `$3, $2',
18 eval($3 > $2), 1, `$1, $3', `$1, $2'), shift(shift(shift($@))))')')
20 patsubst(defn(`input'), `\([^;]*\);', `line(`\1')')
22 define(`chew', `line(substr(`$1', 0, index(`$1', `;')))define(`tail',
23 substr(`$1', incr(index(`$1', `;'))))ifelse(index(defn(
24 `tail'), `;'), -1, `', `$0(defn(`tail'))')')
25 define(`split', `ifelse(eval($1 < 250), 1, `chew(`$2')', `$0(eval($1/2),
26 substr(`$2', 0, eval($1/2)))$0(eval(len(defn(`tail')) + $1 - $1/2),
27 defn(`tail')substr(`$2', eval($1/2)))')')
28 split(len(defn(`input')), defn(`input'))