1 divert(-1)dnl -*- m4 -*-
2 # Usage: m4 [-Dhashsize=H] [-Dfile=day3.input] day3.m4
3 # Optionally use -Dverbose=1 to see some progress
4 # Optionally use -Dalgo=brute|sweep to control algorithm
6 include(`common.m4')ifelse(common(3, 65537), `ok', `',
7 `errprint(`Missing common initialization
10 ifdef(`algo', `', `define(`algo', `sweep')')
12 define(`input', translit((include(defn(`file'))), nl`@,x# ()', `;:::'))
14 define(`line', `_$0(translit(`$1', `:', `,'))')
15 define(`_line', `define(`cnt', `$1')pushdef(`inst', ``$1',`$2','eval(
16 `$2+$4-1')`,`$3','eval(`$3+$5-1'))')
18 patsubst(defn(`input'), `\([^;]*\);', `line(`\1')')
20 define(`_chew', `line(substr(`$1', 0, index(`$1', `;')))define(`tail',
21 substr(`$1', incr(index(`$1', `;'))))ifelse(index(defn(`tail'),
22 `;'), -1, `', `$0(defn(`tail'))')')
23 define(`chew', `ifelse(eval(`$1 < 45'), 1, `_$0(`$2')', `$0(eval(`$1/2'),
24 substr(`$2', 0, eval(`$1/2')))$0(eval(len(defn(`tail'))` + $1 - $1/2'),
25 defn(`tail')substr(`$2', eval(`$1/2')))')')
26 chew(len(defn(`input')), translit(defn(`input'), nl, `;'))
29 ifelse(algo, `brute', `
30 output(1, `using brute-force cell visits')
32 define(`bump', ``define(`part1', incr(part1))pushdef(`$2$3')define(`c$1')'')
33 define(`claim', `forloop($3, $4, `_$0(`$1', `$2', ', `)')')
34 define(`_claim', `ifdef(`g$2_$3', `g$2_$3`'define(`c$1')', `define(`g$2_$3',
35 bump(`$1', `$', `0'))')')
36 define(`loop', `ifdef(`inst', `_$0(inst)popdef(`inst')$0()')')
37 define(`_loop', `forloop($2, $3, `claim(`$1', ', `, `$4', `$5')')')
41 output(1, `using sweep lines tracing')
44 define(`merge', `forloop($3, $4, `_$0(`$1', `$2',', `)')')
45 define(`_merge', `$1(`$2', $3, defn(`x$3'))')
46 define(`use', `ifelse(`$2', `', `popdef(`x$1')', `define(`x$1', `$2')')')
48 define(`claim', `use(`$2', ifelse(`$3', `', `$1', `ifelse(index(`$3', `,'),
49 `-1', `define(`c$3')define(`w', incr(w))')define(`c$1')`$3,$1''))')
50 define(`drop', `use(`$2', ifelse(`$3', `$1', `', `ifelse(len(translit(`$3',
51 `,0123456789', -)), 1, `define(`w', decr(w))')quote(shift(_$0(`$1',$3)))'))')
52 define(`_drop', `ifelse(`$3', `', `', `$1', `$2', `,shift(shift($@))',
53 `,`$2'$0(`$1', shift(shift($@)))')')
54 define(`do', `_$0($1)define(`part1', eval(part1 + w))')
55 define(`_do', `ifdef(`row$1', `row$1`'popdef(`row$1')$0(`$1')')')
57 define(`divvy', `ifdef(`inst', `_$0(inst)popdef(`inst')$0()')')
58 define(`_divvy', `pushdef(`row$2', `merge(`claim', `$1', `$4', `$5')')pushdef(
59 `row'incr(`$3'), `merge(`drop', `$1', `$4', `$5')')')
61 forloop_arg(0, 999, `do')
64 errprintn(`unrecognized -Dalgo= value')m4exit(1)
67 define(`find', `ifdef(`c$1', `', `define(`part2', `$1')')')
68 forloop_arg(1, cnt, `find')