this repo has no description
1<!-- vim:set ft=markdown: -->
2
3<!-- livebook:{"persist_outputs":true} -->
4
5# Day 14
6
7```elixir
8[polymer_raw, subs] =
9 File.read!("day14.txt")
10 |> String.split("\n\n")
11
12<<first, _::binary>> = polymer_raw
13
14polymer =
15 {first,
16 polymer_raw
17 |> String.to_charlist()
18 |> Enum.chunk_every(2, 1, :discard)
19 |> Enum.frequencies()}
20
21subs =
22 subs
23 |> String.trim()
24 |> String.split(["\n", " -> "])
25 |> Enum.chunk_every(2)
26 |> Map.new(fn [pair, <<new>>] -> {String.to_charlist(pair), new} end)
27
28defmodule Day14 do
29 def expand({hd, polymer}, subs) do
30 new =
31 polymer
32 |> Enum.reduce(%{}, fn {[a, b] = pair, count}, acc ->
33 s = Map.fetch!(subs, pair)
34
35 acc
36 |> Map.update([a, s], count, &(&1 + count))
37 |> Map.update([s, b], count, &(&1 + count))
38 end)
39
40 {hd, new}
41 end
42
43 def expand_naive(polymer, subs) do
44 polymer
45 |> to_charlist()
46 |> Enum.chunk_every(2, 1, :discard)
47 |> Enum.flat_map(fn [a, b] = pair ->
48 [a, subs[pair], b]
49 end)
50 |> List.to_string()
51 end
52
53 def frequencies({hd, polymer}) do
54 polymer
55 |> Enum.reduce(%{hd => 1}, fn {[_, b], count}, acc ->
56 Map.update(acc, b, count, &(&1 + count))
57 end)
58 end
59end
60```
61
62```output
63{:module, Day14, <<70, 79, 82, 49, 0, 0, 13, ...>>, {:frequencies, 1}}
64```
65
66## Task 1
67
68```elixir
69{{_, min}, {_, max}} =
70 1..10
71 |> Enum.reduce(polymer, fn _, acc ->
72 Day14.expand(acc, subs)
73 end)
74 |> Day14.frequencies()
75 |> Enum.min_max_by(&elem(&1, 1))
76
77# 2768
78max - min
79```
80
81```output
822768
83```
84
85## Task 2
86
87```elixir
88{{_, min}, {_, max}} =
89 1..40
90 |> Enum.reduce(polymer, fn _, acc ->
91 Day14.expand(acc, subs)
92 end)
93 |> Day14.frequencies()
94 |> Enum.min_max_by(&elem(&1, 1))
95
96max - min
97```
98
99```output
1002914365137499
101```