diff options
author | Justin Wernick <j.wernick@eyeo.com> | 2024-10-10 16:56:46 +0200 |
---|---|---|
committer | Justin Wernick <j.wernick@eyeo.com> | 2024-10-10 16:56:46 +0200 |
commit | 627051329630ca122f4f35274d360040c229d279 (patch) | |
tree | 4ac50a3288f7e617a72450fcedb2ba8115d166c1 | |
parent | bb3530248a831e5bb34b66f44eb2e6904b07c272 (diff) |
Day 19 part 1
-rw-r--r-- | 2015/day19.exs | 37 |
1 files changed, 37 insertions, 0 deletions
diff --git a/2015/day19.exs b/2015/day19.exs new file mode 100644 index 0000000..2aae946 --- /dev/null +++ b/2015/day19.exs @@ -0,0 +1,37 @@ +{replacements, medicine} = + File.stream!("inputs/day19.txt") + |> Stream.map(&String.trim/1) + |> Stream.filter(&(&1 != "")) + |> Stream.map(fn line -> + case Regex.run(~r/(\w+) => (\w+)/, line) do + [_, from, to] -> {:replacement, from, to} + _ -> {:start, line} + end + end) + |> Enum.reduce({[], nil}, fn + {:replacement, from, to}, {replacements, start} -> {[{from, to} | replacements], start} + {:start, start}, {replacements, _start} -> {replacements, start} + end) + +nextGen = fn start -> + Enum.flat_map(0..(String.length(start) - 1), fn offset -> + {beforeReplace, replaceStart} = String.split_at(start, offset) + + Enum.filter(replacements, fn {from, _} -> String.starts_with?(replaceStart, from) end) + |> Enum.map(fn {from, to} -> + {^from, afterReplace} = String.split_at(replaceStart, String.length(from)) + <<beforeReplace <> to <> afterReplace>> + end) + end) + |> Enum.uniq() +end + +calibration = nextGen.(medicine) + +IO.puts("Calibration size: #{length(calibration)}") + +medicineGeneration = + Stream.iterate(["e"], fn gen -> Enum.flat_map(gen, &nextGen.(&1)) |> Enum.uniq() end) + |> Enum.find_index(fn gen -> Enum.any?(gen, &(&1 == medicine)) end) + +IO.puts("The Medicine generation: #{medicineGeneration}") |