1 divert(-1)dnl -*- m4 -*-
2 # Usage: m4 [-Dhashsize=H] [-Dfile=day13.input] day13.m4
3 # Optionally use -Dverbose=1 to see some progress
5 include(`common.m4')ifelse(common(13, 65537), `ok', `',
6 `errprint(`Missing common initialization
9 define(`D', defn(`define'))define(`U', defn(`popdef'))
10 define(`I', defn(`ifelse'))define(`F', defn(`ifdef'))
11 define(`P', defn(`incr'))define(`M', defn(`decr'))
12 define(`N', defn(`defn'))define(`E', defn(`eval'))define(`S', defn(`shift'))
13 define(`input', translit(include(defn(`file')), nl` +\/^>v<|-', `01234nesw11'))
14 define(`x', 0)define(`y', 0)define(`cnt', 0)
15 define(`v0', `D(`x', 0)D(`y',P(`$2'))')
16 define(`v1', `D(`x',P(`$1'))')
17 define(`v2', `D(`g$1_$2',`2')v1(`$1')')
18 define(`v3', `D(`g$1_$2',`3')v1(`$1')')
19 define(`v4', `D(`g$1_$2',`4')v1(`$1')')
20 define(`cart', `D(`c$4',`$1,$2,`$3',`l'')D(`c$1_$2',`$4')D(`l',
21 N(`l')`,$4')D(`cnt',P(`$4'))v1(`$1')')
22 define(`vn', `cart($@,`n',cnt)')
23 define(`ve', `cart($@,`e',cnt)')
24 define(`vs', `cart($@,`s',cnt)')
25 define(`vw', `cart($@,`w',cnt)')
27 patsubst(defn(`input'), `.', `v\&(x,y)')
29 define(`chew', `ifelse(`$1', `1', `v$2(x,y)', `$0(eval(`$1/2'), substr(
30 `$2', 0, eval(`$1/2')))$0(eval(`$1-$1/2'), substr(`$2', eval(`$1/2')))')')
31 chew(len(defn(`input')), defn(`input'))
33 define(`lt', `E(`$2<$6||($2==$6&&$1<$5)')')
34 define(`sort', `I(`$2',,`,`$1'',`I(lt(c$1,c$2),1,`,$@',
35 `,`$2'$0(`$1',S(S($@)))')')')
36 define(`act', `I(`$2',,,`F(`d$2',,`move(c$2,`$2')')$0(S($@))')')
37 define(`crash', `F(`part1', `', `D(`part1', `$1,$2')')D(`d'c$1_$2)D(`d$3')U(
38 `c$1_$2')D(`left', M(M(left)))')
39 define(`move', `U(`c$1_$2')_$0($0$3(`$1',`$2'),`$3',`$4',`$5')')
40 define(`_move', `F(`c$1_$2',`crash(`$1',`$2',`$5')',`D(`c$1_$2',
41 `$5')D(`c$5',`$1,$2,'turn(`$3',`$4',N(`g$1_$2')))D(`l',N(`l')`,$5')')')
42 define(`moven', ``$1',M(`$2')')
43 define(`movee', `P(`$1'),`$2'')
44 define(`moves', ``$1',P(`$2')')
45 define(`movew', `M(`$1'),`$2'')
46 define(`turn', `I(`$3',,```$1',`$2''',`$3',`2',`N(`t$1$2')',
47 `N(`t$3$1')`,`$2''')')
48 define(`tnl', ``w',`f'')define(`tnf', ``n',`r'')define(`tnr', ``e',`l'')
49 define(`tel', ``n',`f'')define(`tef', ``e',`r'')define(`ter', ``s',`l'')
50 define(`tsl', ``e',`f'')define(`tsf', ``s',`r'')define(`tsr', ``w',`l'')
51 define(`twl', ``s',`f'')define(`twf', ``w',`r'')define(`twr', ``n',`l'')
52 define(`t3n', ``w'')define(`t3e', ``s'')
53 define(`t3s', ``e'')define(`t3w', ``n'')
54 define(`t4n', ``e'')define(`t4e', ``n'')
55 define(`t4s', ``w'')define(`t4w', ``s'')
56 define(`_tick', `I(`$2', `', `D(`l')', `sort($2$0(S($@)))')')
57 define(`tick', `act(_$0(l))I($2, 1, `P(`$1')', `I(E(
58 `$1%1000'), 0, `output(1, `...$1 'left)')$0(P(`$1'), `$2')')')
60 tick(tick(0, `ifdef(`part1', 1)'), `left')
61 define(`find', `ifdef(`d$1', `', `_$0(c$1)')')
62 define(`_find', `define(`part2', `$1,$2')')
63 forloop_arg(0, cnt-1, `find')