Skip to content

Instantly share code, notes, and snippets.

@sasa1977
Created December 12, 2017 08:02
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/3345136670632283ac58bc1d9a7ed714 to your computer and use it in GitHub Desktop.
Save sasa1977/3345136670632283ac58bc1d9a7ed714 to your computer and use it in GitHub Desktop.
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