1 divert(-1)dnl -*- m4 -*-
2 # Usage: m4 [-Dfile=day03.input] day03.m4
4 include(`common.m4')ifelse(common(03), `ok', `',
5 `errprint(`Missing common initialization
8 define(`input', translit(include(defn(`file')), nl`#', `;\'))
9 define(`x', 1)define(`y', 1)define(`n', 0)define(`g', 0)
10 define(`splat', `define(`s$1_$4')define(`s$2_$4')define(`s$3_$4')define(
11 `s$1_$5')define(`s$3_$5')define(`s$1_$6')define(`s$2_$6')define(
12 `s$3_$6')ifelse(`$7', `*', `define(`g'g, `$@')define(`g', incr(g))')')
14 define(`_num', `define(`n$4', `$1, $5, $3, $4')define(`N$4', eval(10*N$4+$6))')
15 define(`num', `ifdef(`n$1_$3', `_$0(first(`n'n$1_$3), $2, $4)', `define(`n',
16 incr(n))define(`n'n, `$2, $2, $3, 'n)define(`N'n, $4)')define(`n$2_$3', n)')
17 define(`do', `ifelse($3, `;', `define(`x', 1)define(`y', incr($2))',
18 `ifelse($3, `.', `', index(0123456789, $3), -1, `splat(decr($1), $1, incr($1),
19 decr($2), $2, incr($2), $3)', `num(decr($1), $@)')define(`x', incr($1))')')
22 patsubst(defn(`input'), `.', `do(x, y, `\&')')
24 define(`chew', `ifelse($1, 1, `do(x, y, `$2')', `$0(eval($1/2), substr(
25 `$2', 0, eval($1/2)))$0(eval($1-$1/2), substr(`$2', eval($1/2)))')')
26 chew(len(defn(`input')), defn(`input'))
29 define(`_n', `ifdef(`s$1_$3', `+N$4', `ifdef(`s$2_$3', `+N$4')')')
30 define(`c', `ifdef(`n$2_$4', `,N(n$2_$4)', `ifdef(`n$1_$4', `,N(n$1_$4)')ifdef(
31 `n$3_$4', `,N(n$3_$4)')')')
32 define(`count', `ifelse(`$#', 3, `+$2*$3')')
33 define(`_g', `count(c($1, $2, $3, $4)c($1, $2, $3, $5)c($1, $2, $3, $6))')
34 define(`part1', eval(forloop(1, n, `_n(first(`n'', `))')))
35 define(`part2', eval(forloop(0, decr(g), `_g(first(`g'', `))')))