1 divert(-1)dnl -*- m4 -*-
2 # Usage: m4 [-Dinput=NNN] [-Dfile=day3.input] day3.m4
4 include(`common.m4')ifelse(common(3), `ok', `',
5 `errprint(`Missing common initialization
8 ifdef(`input', `', `define(`input', translit(include(defn(`file')), nl))')
9 define(`find', `ifelse(eval(`$1*$1<$2'), 1, `$0(incr(incr($1)), $2)', $1)')
10 define(`abs', `ifelse(eval($1 < 0), 1, -($1), $1)')
11 define(`distance', `define(`base', find(1, $1))define(`last',
12 eval(base*base))define(`side', eval(base-1))ifelse($1, 1, 0, `eval(base/2 +
13 abs((last - $1)%side - side/2))')')
14 define(`part1', distance(input))
15 define(`idx', `eval(100*($2+50)+$1)')
16 define(`set', `define(`g'idx($1, $2), $3)eval($3 > 'input`)')
17 define(`get', `_$0(`g'idx($1, $2))')
18 define(`_get', `ifdef(`$1', `$1', 0)')
20 define(`near', `eval(get(decr($1), decr($2)) + get(decr($1), $2) +
21 get(decr($1), incr($2)) + get($1, decr($2)) + get($1, incr($2)) +
22 get(incr($1), decr($2)) + get(incr($1), $2) + get(incr($1), incr($2)))')
23 define(`next', `first(`$0'eval(`4*($4==$3*$3) + ($3*$3-$4-1)/($3-1)'))($@)')
24 define(`next0', `incr($1), $2, $3')
25 define(`next1', `$1, decr($2), $3')
26 define(`next2', `decr($1), $2, $3')
27 define(`next3', `$1, incr($2), $3')
28 define(`next4', `incr($1), $2, incr(incr($3))')
29 define(`do', `ifelse(set($1, $2, near($1, $2)), 1, `define(`part2', get($1,
30 $2))', `$0(next($1, $2, $3, $4), incr($4))')')