2021: consistent sorting of file names
[aoc_eblake.git] / 2021 / day03.m4
blobd942876580faa23d234f74265da33237947485d3
1 divert(-1)dnl -*- m4 -*-
2 # Usage: m4 [-Dfile=day03.input] day03.m4
4 include(`common.m4')ifelse(common(03), `ok', `',
5 `errprint(`Missing common initialization
6 ')m4exit(1)')
8 define(`input', translit(include(defn(`file')), nl, `;'))
9 define(`width', index(defn(`input'), `;'))
10 define(`max', eval((1<<width)-1))
11 ifdef(`__gnu__', `
12   define(`b2d', `eval(`0b$1')')
13   patsubst(defn(`input'), `\([^;]*\);', `define(`v'eval(`0b\1'))')
14 ', `
15   define(`b2d', `_$0(0, `$1')')define(`_b2d', `ifelse(`$2', `', `$1',
16     `$0(eval($1*2+substr(`$2', 0, 1)), substr(`$2', 1))')')
17   define(`half', `eval($1/'width`/2*'width`)')
18   define(`chew', `ifelse($1, 'width`, `define(`v'b2d(`$2'))', `$0(half($1),
19     substr(`$2', 0, half($1)))$0(eval($1-half($1)), substr(`$2', half($1)))')')
20   chew(eval(len(defn(`input'))/(width+1)*width), translit(defn(`input'), `;'))
22 define(`bump', `define(`$1', incr($1))')
23 define(`search', `define(`z', 0)define(`o', 0)forloop($1, $2, `_$0(', `, $3)')')
24 define(`_search', `ifdef(`v$1', `bump(ifelse(eval($1&$2), 0, ``z'', ``o''))')')
26 define(`bit', `search(0, 'max`, (1<<('width`-$1)))eval(o > z)')
27 define(`do', `eval($1*(max^$1))')
28 define(`part1', do(b2d(forloop_arg(1, width, `bit'))))
30 define(`bit', `search(lo, hi, (1<<('width`-$1)))ifelse(eval($2), 1,
31   `define(`lo', eval(lo+(1<<(''width``-$1))))',
32   `define(`hi', eval(hi-(1<<(''width``-$1))))')')
33 define(`do', `define(`lo', 0)define(`hi', max)forloop(1, width,
34   `bit(', `, `$1')')lo')
35 define(`part2', eval(do(`o>=z') * do(`o&&(!z||z>o)')))
37 ifelse(`dnl golfing variant of part 1:
38 define(d,defn(pushdef))d(B,`d(`$1',1defn(`$1'))')d(b,`B(`x'y)a()')d(a,`B(`y')')d(c,`B(`z')d(`y')')patsubst(translit(include(f),01
39 ,abc),.,\&())popdef(`y')d(l,`ifelse($2,y,$1*(`0b'y^$1),`l(($1+$1+(len(x$2)>len(z)/2)),1$2)')')eval(l(0))
42 divert`'part1
43 part2