@@ -48,6 +48,7 @@ defmodule AdventOfCode.Day14 do
4848
4949 def part2 ( args ) do
5050 { start , key } = parse ( args )
51+ first_last = { List . first ( start ) , List . last ( start ) }
5152
5253 all_zeroes = Map . map ( key , fn _ -> 0 end )
5354 counts = Enum . chunk_every ( start , 2 , 1 , :discard )
@@ -56,7 +57,7 @@ defmodule AdventOfCode.Day14 do
5657 end )
5758
5859 { min , max } = faster_polymer ( counts , key , 1 .. 40 )
59- |> find_min_max ( )
60+ |> find_min_max ( first_last )
6061
6162 max - min
6263 end
@@ -110,16 +111,37 @@ defmodule AdventOfCode.Day14 do
110111 Figures out the most and least common letters and how many
111112 iex> counts = %{{"N", "N"} => 0, {"N", "C"} => 1, {"C", "N"} => 1, {"N", "B"} => 1,
112113 ...> {"B","C"} => 1, {"C","H"} => 1, {"H","B"} => 1, {"C", "B"} => 0}
113- iex> AdventOfCode.Day14.find_min_max(counts)
114+ iex> AdventOfCode.Day14.find_min_max(counts, {"B", "C"} )
114115 {1, 2}
116+
117+ iex> counts = %{{"N", "N"} => 0, {"N", "C"} => 1, {"C", "N"} => 1, {"N", "B"} => 1,
118+ ...> {"B","C"} => 1, {"C","H"} => 1, {"H","B"} => 1, {"C", "B"} => 0}
119+ iex> AdventOfCode.Day14.find_min_max(counts, {"B", "B"})
120+ {1, 3}
115121 """
116- def find_min_max ( counts ) do
122+ def find_min_max ( counts , first_last ) do
117123 { { _ , min } , { _ , max } } = Enum . reduce ( counts , % { } , fn { { first , second } , count } , total ->
118124 Map . update ( total , first , count , & ( & 1 + count ) )
119125 |> Map . update ( second , count , & ( & 1 + count ) )
120126 end )
121127 |> Map . map ( fn { _ , x } -> round ( x / 2 ) end )
128+ |> handle_first_last ( first_last )
122129 |> Enum . min_max_by ( fn { _letter , quant } -> quant end )
123130 { min , max }
124131 end
132+
133+ @ doc """
134+ iex> AdventOfCode.Day14.handle_first_last(%{"B" => 3, "C" => 4, "H" => 5}, {"B", "C"})
135+ %{"B" => 3, "C" => 4, "H" => 5}
136+
137+ iex> AdventOfCode.Day14.handle_first_last(%{"B" => 3, "C" => 4, "H" => 5}, {"B", "B"})
138+ %{"B" => 4, "C" => 4, "H" => 5}
139+ """
140+ def handle_first_last ( counts , { a , a } ) do
141+ as = counts [ a ]
142+ Map . replace ( counts , a , as + 1 )
143+ end
144+
145+ def handle_first_last ( counts , { _first , _last } ) , do: counts
146+
125147end
0 commit comments