From 46f3ae87dc06a810d704f08ce2edf4610570ac5f Mon Sep 17 00:00:00 2001 From: sloane Date: Tue, 26 Nov 2024 14:25:14 -0500 Subject: [PATCH] solve 2015 day 19 pt 2 --- 2015/lib/2015/19.ex | 24 ++++++++++++++++++++++++ README.md | 2 +- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/2015/lib/2015/19.ex b/2015/lib/2015/19.ex index bb53976..416ee9a 100644 --- a/2015/lib/2015/19.ex +++ b/2015/lib/2015/19.ex @@ -49,5 +49,29 @@ aoc 2015, 19 do end def p2 do + {mappings, molecule} = input() + + find_shortest_path(molecule, invert(mappings)) + end + + defp find_shortest_path(molecule, replacements, steps \\ 0) + defp find_shortest_path("e", _replacements, steps), do: steps + + defp find_shortest_path(molecule, replacements, steps) do + {from, to} = + Enum.find(replacements, fn {from, _} -> + String.contains?(molecule, from) + end) + + molecule = String.replace(molecule, from, to, global: false) + + find_shortest_path(molecule, replacements, steps + 1) + end + + defp invert(mappings) do + for {from, tos} <- mappings, to <- tos do + {to, from} + end + |> Enum.sort_by(fn {from, _} -> String.length(from) end, :desc) end end diff --git a/README.md b/README.md index 93de9fa..f11f9c4 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ | Year | Stars | Languages | | - | - | - | -| [2015] | **37/50** 🌟 | Elixir | +| [2015] | **38/50** 🌟 | Elixir | | 2016 | | | | [2017] | **18/50** 🌟 | Haskell | | 2018 | | |