this repo has no description
1<!-- vim:ft=markdown --> 2 3<!-- livebook:{"persist_outputs":true} --> 4 5# Day 21 6 7## Section 8 9```elixir 10input = File.read!("day21.txt") 11 12[[_, p1], [_, p2]] = Regex.scan(~r/: (\d)/, input) 13 14p1 = String.to_integer(p1) 15p2 = String.to_integer(p2) 16 17{p1, p2} 18``` 19 20```output 21{3, 5} 22``` 23 24```elixir 25round = 26 Stream.unfold(0, &{&1, &1 + 1}) 27 |> Stream.scan({{0, p1}, {0, p2}}, fn n, {{s, p}, other} -> 28 p = rem(p - 1 + 6 + n * 9, 10) + 1 29 30 {other, {s + p, p}} 31 end) 32 |> Enum.take_while(fn {{s, _}, {_, _}} -> s < 1000 end) 33 34{rounds, {{loser, _}, _}} = {length(round), List.last(round)} 35 36rounds * 3 * loser 37``` 38 39```output 40720750 41``` 42 43```elixir 44defmodule Day21.Task2 do 45 def play(p1, p2) do 46 tid = :ets.new(__MODULE__, []) 47 {a, b} = cached_round({p1 - 1, 0}, {p2 - 1, 0}, tid) 48 :ets.delete(tid) 49 max(a, b) 50 end 51 52 defp cached_round(a, b, tid) do 53 case :ets.lookup(tid, {a, b}) do 54 [{_, v}] -> 55 v 56 57 [] -> 58 value = round(a, b, tid) 59 60 :ets.insert(tid, {{a, b}, value}) 61 62 value 63 end 64 end 65 66 defp round({_, s}, _, _) when s >= 21, do: {1, 0} 67 defp round(_, {_, s}, _) when s >= 21, do: {0, 1} 68 69 defp round({pos, score}, p2, tid) do 70 for a <- 1..3, b <- 1..3, c <- 1..3, reduce: {0, 0} do 71 {wins1, wins2} -> 72 next = rem(pos + a + b + c, 10) 73 74 {nscore2, nscore1} = 75 cached_round( 76 p2, 77 {next, score + next + 1}, 78 tid 79 ) 80 81 {wins1 + nscore1, wins2 + nscore2} 82 end 83 end 84end 85``` 86 87```output 88{:module, Day21.Task2, <<70, 79, 82, 49, 0, 0, 12, ...>>, {:round, 3}} 89``` 90 91```elixir 92Day21.Task2.play(p1, p2) 93``` 94 95```output 96275067741811212 97```