day 24 optimize
[aoc_eblake.git] / 2023 / day06.m4
blob0f0e7850a548454f42eac7cb56f52dbb3dbc5e3a
1 divert(-1)dnl -*- m4 -*-
2 # Usage: m4 [-Dfile=day06.input] day06.m4
4 include(`common.m4')ifelse(common(06), `ok', `',
5 `errprint(`Missing common initialization
6 ')m4exit(1)')
8 # TODO: Idea for optimization: implement arbitrary-width division and
9 # square root, then directly land on the result by solving the
10 # quadratic equation, rather than binary searching for an answer.
12 include(`math64.m4')
13 define(`input', translit(include(defn(`file')), Tsemantic))
14 define(`half', `_$0(mul(5, $1))')define(`_half', `substr($1, 0, decr(len($1)))')
15 define(`_search', `ifelse(, $@, lt64(mul64($4, eval($1 - $4)), $2), 0,
16   `search($1, $2, $3, $4)', `search($1, $2, $4, $5)')')
17 define(`search', `_$0($1, $2, $3, half(add($3, $4)), $4)')
18 define(`count', `eval($1-search($1, $2, 0, half($1))*2+1)')
19 define(`zip', `ifelse($1$2, ()(), , first$1,, `zip((shift$1),$2)', first$2,,
20   `zip($1,(shift$2))', `,count(first$1, first$2)zip((shift$1),(shift$2))')')
21 define(`part1', mul(1zip(translit(input, :D nl, (,,)))))
22 define(`part2', count(translit(input, nl :D, `,')))
24 divert`'part1
25 part2