Created
December 12, 2017 08:02
-
-
Save sasa1977/3345136670632283ac58bc1d9a7ed714 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 Day12 do | |
def part1(), do: | |
connections() |> group("0") |> Enum.count() | |
def part2(), do: | |
connections() |> all_groups() |> Enum.count() | |
defp connections(), do: | |
"input.txt" | |
|> File.stream!() | |
|> Stream.map(&String.trim/1) | |
|> Stream.map(&String.split(&1, " <-> ")) | |
|> Stream.map(fn [element, neighbours] -> {element, String.split(neighbours, ", ")} end) | |
|> Map.new() | |
defp all_groups(connections), do: | |
Enum.reduce( | |
Map.keys(connections), | |
[], | |
fn program, groups -> | |
if Enum.any?(groups, &MapSet.member?(&1, program)), | |
do: groups, | |
else: [group(connections, program) | groups] | |
end | |
) | |
defp group(connections, program) do | |
{neighbours, other_connections} = Map.pop(connections, program, MapSet.new()) | |
Enum.reduce(neighbours, MapSet.new([program]), &MapSet.union(&2, group(other_connections, &1))) | |
end | |
end | |
Day12.part1() |> IO.inspect | |
Day12.part2() |> IO.inspect |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment