Skip to content

Instantly share code, notes, and snippets.

@sasa1977
Last active December 24, 2017 13:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sasa1977/7c5c681d51f4a070455b5b2a02405c4f to your computer and use it in GitHub Desktop.
Save sasa1977/7c5c681d51f4a070455b5b2a02405c4f to your computer and use it in GitHub Desktop.
defmodule Day24 do
def part1(), do:
connections() |> all_bridges() |> Stream.map(&(&1.strength)) |> Enum.max()
def part2(), do:
(connections() |> all_bridges() |> Enum.max_by(&{&1.length, &1.strength})).strength
defp all_bridges(connections), do:
Enum.reduce(Map.get(connections, 0), [], &bridges(connections, {0, &1}, &2))
defp bridges(connections, component, bridges, bridge \\ %{strength: 0, length: 0}) do
bridge = collect_component(bridge, component)
case pop_ports(connections, component) do
nil -> [bridge | bridges]
{next_ports, remaining_connections} ->
Enum.reduce(next_ports, bridges, &bridges(remaining_connections, next_component(component, &1), &2, bridge))
end
end
defp collect_component(bridge, {port_a, port_b}), do:
%{bridge |
length: bridge.length + 1,
strength: bridge.strength + port_a + port_b
}
defp pop_ports(connections, {port_a, port_b}) do
%{^port_a => connected_a, ^port_b => connected_b} = connections
connections = %{connections |
port_a => MapSet.delete(connected_a, port_b),
port_b => MapSet.delete(connected_b, port_a)
}
ports = Map.get(connections, port_b, MapSet.new())
if MapSet.size(ports) == 0, do: nil, else: {ports, connections}
end
defp next_component({_port_a, port_b}, connected_port), do: {port_b, connected_port}
defp connections() do
"input.txt"
|> File.stream!()
|> Stream.map(&String.trim/1)
|> Stream.flat_map(&String.split(&1, "/"))
|> Stream.map(&String.to_integer/1)
|> Stream.chunk_every(2)
|> Enum.reduce(%{},
fn [a, b], connections ->
connections
|> Map.update(a, MapSet.new([b]), &MapSet.put(&1, b))
|> Map.update(b, MapSet.new([a]), &MapSet.put(&1, a))
end
)
end
end
Day24.part1() |> IO.inspect
Day24.part2() |> IO.inspect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment