1 divert(-1)dnl -*- m4 -*-
2 # Usage: m4 [-Dfile=day08.input] day08.m4
4 include(`common.m4')ifelse(common(08), `ok', `',
5 `errprint(`Missing common initialization
8 define(`input', translit(include(defn(`file')), nl, `;'))
9 define(`_reset', `define(`l$1', 0)popdef(`d$1')popdef(`s$1')popdef(
10 `n'm$1)popdef(`m$1')')
11 define(`reset', `define(`state', 0)forloop_arg(0, 9, `_$0')define(`buf')')
12 reset()forloop(11, 14, `define(`l'', `, 0)')
13 define(`part1', 0)define(`part2', 0)
15 define(`dolet', `define(`buf', defn(`buf')`+$2')define(`l$1', incr(l$1))')
16 define(`doa', `dolet($1, `1')')
17 define(`dob', `dolet($1, `10')')
18 define(`doc', `dolet($1, `100')')
19 define(`dod', `dolet($1, `1000')')
20 define(`doe', `dolet($1, `10000')')
21 define(`dof', `dolet($1, `100000')')
22 define(`dog', `dolet($1, `1000000')')
23 define(`do0', `define(`d$1', eval(buf))define(`buf')')
24 forloop(1, 9, `define(`do'', `, defn(`do0'))')
25 define(`map', `define(`n$1', $2)define(`m$2', $1)')
26 define(`pass1', `_$0(l$1, d$1)')
27 define(`_pass1', `ifelse($1, 2, `map($2, 1)', $1, 3, `map($2, 7)', $1, 4,
28 `map($2, 4)', $1, 7, `map($2, 8)')')
29 define(`pass2', `define(`s2', _$0($1, 6))define(`s5', _$0($1, 4))define(
30 `s6', _$0($1, 9))define(`s3', eval(m1-s6))define(`s4', eval(m4-s2-s3-s6))')
31 define(`_pass2', `substr(1000000, 0, eval(7-index($1, $2)))')
32 define(`pass3', `_$0(l$1, d$1)')
33 define(`_pass3', `ifelse($1, 5, `$0$1($2)', $1, 6, `$0$1($2)')')
34 define(`_pass35', `ifelse(eval(!(`0x$1&0x's5)), 0, `map($1, 2)',
35 eval(!(`0x$1&0x's2)), 0, `map($1, 5)', `map($1, 3)')')
36 define(`_pass36', `ifelse(eval(`0x$1&0x's4), 0, `map($1, 0)',
37 eval(`0x$1&0x's3), 0, `map($1, 6)', `map($1, 9)')')
38 define(`do10', `forloop_arg(0, 9, `pass1')pass2(eval(forloop(0, 9, `+defn(`d'',
39 `)')))forloop_arg(0, 9, `pass3')')
40 define(`use', `ifelse(index(`023569', $1), -1, `define(`part1',
41 incr(part1))')define(`part2', eval(part2+$1substr(`___________000', $2)))')
42 define(`do11', `use(defn(`n'eval(buf)), $1)define(`buf')')
43 forloop(12, 14, `define(`do'', `, defn(`do11'))')
44 define(`do', `ifelse(`$2', `;', `do$1($1)reset()', `$2', ` ', `do$1($1)define(
45 `state', incr($1))', `$2', `|', `', `do$2($1)')')
48 patsubst(defn(`input'), `.', `do(state, `\&')')
50 define(`chew', `ifelse($1, 1, `do(state, `$2')', `$0(eval($1/2), substr(
51 `$2', 0, eval($1/2)))$0(eval($1-$1/2), substr(`$2', eval($1/2)))')')
52 chew(len(defn(`input')), defn(`input'))
55 ifelse(`dnl golfing variant of part 1:
56 eval(define(d,defn(define))translit(include(f),b-g|d(aa,+1)d(aaa,+1)d(aaaa,+1)d(aaaaa)d(aaaaaa)d(aaaaaaa,+1)d(x,-4),aaaaaax))
58 # cut -b61-<f|tr \ \\n|egrep -c "^...?.?.{5}?$"