-
-
Save sasa1977/d70f0986bf72bb94048d37843d11b4a4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Day5 do | |
def part1(), do: polymer() |> react() |> polymer_size() | |
def part2() do | |
polymer() | |
|> unique_units() | |
|> Stream.map(&remove_unit(polymer(), &1)) | |
|> Stream.map(&react/1) | |
|> Stream.map(&polymer_size/1) | |
|> Enum.min() | |
end | |
defp unique_units(polymer) do | |
polymer | |
|> Stream.flat_map(&([&1] |> to_string() |> String.upcase() |> to_charlist())) | |
|> Stream.uniq() | |
end | |
defp remove_unit(polymer, unit), do: Enum.reject(polymer, &(&1 == unit or opposite_polarities?(&1, unit))) | |
defp react([]), do: [] | |
defp react([a | rest]) do | |
case react(rest) do | |
[] -> [a] | |
[b | rest] -> react_pair(a, b) ++ rest | |
end | |
end | |
defp react_pair(a, b), do: if(opposite_polarities?(a, b), do: [], else: [a, b]) | |
defp opposite_polarities?(a, b), do: abs(a - b) == ?a - ?A | |
defp polymer() do | |
"input.txt" | |
|> File.read!() | |
|> to_charlist() | |
|> Enum.reject(&(&1 == ?\n)) | |
end | |
defp polymer_size(polymer), do: length(polymer) | |
end | |
Day5.part1() |> IO.inspect() | |
Day5.part2() |> IO.inspect() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment