1 divert(-1)dnl -*- m4 -*-
2 # Usage: m4 [-Dfile=day05.input] day05.m4
4 include(`common.m4')ifelse(common(05), `ok', `',
5 `errprint(`Missing common initialization
8 define(`input', translit(include(defn(`file')), ` 'nl, `.;'))
9 define(`mark', incr(index(defn(`input'), `;;')))
10 define(`intro', substr(defn(`input'), 0, mark))
12 # First phase: parse into stacks. Assumes no more than 9 stacks in input;
13 # because of the use of translit to map an input line into stack population,
14 # and we are limited to single-letter macro names being beyond j.
15 # Process lines in reverse order to build stacks correctly.
16 define(`n', eval(index(defn(`intro'), `;')`/4+1'))
18 patsubst(defn(`intro'), translit(eval(n*4, 1), 1, .), `pushdef(`line', `\&')')
20 define(`half', `eval($1/(n*4)/2*(n*4))')
21 define(`chew', `ifelse($1, 110, `pushdef(`line', `$2')', `$0(half($1),
22 substr(`$2', 0, half($1)))$0(eval($1-half($1)), substr(`$2', half($1)))')')
23 chew(len(defn(`list')), defn(`list'))
25 define(`u', `ifelse(`$1', `.', `', `pushdef(`s$2', `$1')pushdef(`w$2', `$1')')')
26 define(`prep', `ifdef(`line', `translit(
27 `u(`B',1)u(`F',2)u(`J',3)u(`N',4)u(`R',5)u(`V',6)u(`Z',7)u(`d',8)u(`h',9)',
28 ''dquote(dquote(defn(`ALPHA')))```abcdefghij',
29 defn(`line'))popdef(`line')$0()')')
32 # Second half: Swizzle the stacks per the instructions.
33 # The translit here turns "move A from B to C\n" into "v(A,B,C)"
34 define(`exch', `ifelse(`$1', 0, `', `pushdef(`$3', defn(`$2'))popdef(
35 `$2')$0(decr($1), `$2', `$3')')')
36 define(`v', `exch(`$1', `s$2', `s$3')exch(`$1', `w$2', `tmp')exch(`$1',
38 translit(substr(defn(`input'), incr(mark)), `eft;.mor', `(,,)')
39 define(`part1', forloop(1, n, `defn(`s'', `)'))
40 define(`part2', forloop(1, n, `defn(`w'', `)'))