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(`list', translit((include(defn(`file')),), `,() 'nl, `;'))
9 define(`x', 0)define(`y', 0)define(`dir', `n')
10 define(`Ln', `w')define(`Le', `n')define(`Ls', `e')define(`Lw', `s')
11 define(`Rn', `e')define(`Re', `s')define(`Rs', `w')define(`Rw', `n')
12 define(`in', `ifelse(eval($2 < $3), 1, `eval($1 >= $2 && $1 <= $3)',
13 `eval($1 >= $3 && $1 <= $2)')')
14 define(`check', `_stack_foreach(`$1', `_$0(first(', `), $2, $3, $4)', `t')')
15 define(`_check', `ifelse(in($4, $2, $3), 1, `ifelse(in($1, $5, $6), 1,
16 `define(`part2', dist($1, $4))pushdef(`check')')')')
17 define(`abs', `ifelse(index($1, -), 0, `substr($1, 1)', $1)')
18 define(`dist', `eval(abs($1) + abs($2))')
19 define(`moven', `pushdef(`ns', x`,'y`,'check(`ew', x, decr(y),
20 define(`y', eval(y - $1))y)y)')
21 define(`movee', `pushdef(`ew', y`,'x`,'check(`ns', y, incr(x),
22 define(`x', eval(x + $1))x)x)')
23 define(`moves', `pushdef(`nw', x`,'y`,'check(`ew', x, incr(y),
24 define(`y', eval(y + $1))y)y)')
25 define(`movew', `pushdef(`ew', y`,'x`,'check(`ns', y, decr(x),
26 define(`x', eval(x - $1))x)x)')
27 define(`move', `$0$1($2)')
28 define(`visit', `define(`dir', defn(`$1'dir))move(dir, $2)')
30 patsubst(defn(`list'), `\(.\)\([0-9]*\);', `visit(`\1', \2)')
32 define(`chew', `visit(substr(`$1', 0, 1), substr(`$1', 1, decr(index(`$1',
33 `;'))))define(`tail', substr(`$1', incr(index(`$1', `;'))))ifelse(index(
34 defn(`tail'), `;'), -1, `', `$0(defn(`tail'))')')
35 define(`split', `ifelse(eval($1 < 10), 1, `chew(`$2')', `$0(eval($1/2),
36 substr(`$2', 0, eval($1/2)))$0(eval(len(defn(`tail')) + $1 - $1/2),
37 defn(`tail')substr(`$2', eval($1/2)))')')
38 split(len(defn(`list')), defn(`list'))
40 define(`part1', dist(x, y))