1 divert(-1)dnl -*- m4 -*-
2 # Usage: m4 [-Dfile=day3.input] day3.m4
4 include(`common.m4')ifelse(common(3), `ok', `',
5 `errprint(`Missing common initialization
8 define(`offset', 20000)
10 `define(`l', 0)define(`x', offset)define(`y', offset)foreach(`segment', $@)')
11 define(`segment', `_$0(substr($1, 0, 1), substr($1, 1))')
12 define(`_segment', `visit(l, x, y, move($1, $2)x, y)')
13 define(`move', `define(`l', eval(l + $2))move$1($2)')
14 define(`moveU', `define(`y', eval(y - $1))')
15 define(`moveR', `define(`x', eval(x + $1))')
16 define(`moveD', `define(`y', eval(y + $1))')
17 define(`moveL', `define(`x', eval(x - $1))')
19 define(`input', quote(include(defn(`file'))))
21 define(`visit', `define(`s'segments, `$*')define(`segments', incr(segments))')
22 path(substr(defn(`input'), 0, index(defn(`input'), `
25 define(`part2', eval(l * 2))
28 `eval(($1 < $2 && $3 > $1 && $3 < $2) || ($3 > $2 && $3 < $1))')
30 define(`abs', `ifelse(eval($1 > 0), 1, $1, -($1))')
31 define(`visit', `forloop(0, decr(segments), `_$0(s(', `), $@)')')
32 define(`_visit', `ifelse(ifelse(
33 $2.$8, $4.ninth(shift($@)), `between($7, $9, $2).between($3, $5, $8)',
34 $3.$7, $5.$9, `between($2, $4, $7).between($8, ninth(shift($@)), $3)'),
35 1.1, `intersect($@)')')
36 define(`intersect', `ifelse($2, $4,
37 `_$0($2 - offset, $8 - offset, $1 + abs($8 - $3), $6 + abs($2 - $7))',
38 `_$0($7 - offset, $3 - offset, $1 + abs($7 - $2), $6 + abs($3 - $8))')')
39 define(`_intersect', `check(1, $1, $2)check(2, $3, $4)')
40 define(`check', `_$0(eval(abs($2) + abs($3)), `part$1')')
41 define(`_check', `ifelse(eval($1 < $2), 1, `define(`$2', $1)')')
42 path(translit(quote(substr(defn(`input'), index(defn(`input'), `