Guest User

Untitled

a guest
Dec 14th, 2017
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.95 KB | None | 0 0
  1. defmodule Day12 do
  2. def part1(), do:
  3. connections() |> group("0") |> Enum.count()
  4.  
  5. def part2(), do:
  6. connections() |> all_groups() |> Enum.count()
  7.  
  8. defp connections(), do:
  9. "input.txt"
  10. |> File.stream!()
  11. |> Stream.map(&String.trim/1)
  12. |> Stream.map(&String.split(&1, " <-> "))
  13. |> Stream.map(fn [element, neighbours] -> {element, String.split(neighbours, ", ")} end)
  14. |> Map.new()
  15.  
  16. defp all_groups(connections), do:
  17. Enum.reduce(
  18. Map.keys(connections),
  19. [],
  20. fn program, groups ->
  21. if Enum.any?(groups, &MapSet.member?(&1, program)),
  22. do: groups,
  23. else: [group(connections, program) | groups]
  24. end
  25. )
  26.  
  27. defp group(connections, program) do
  28. {neighbours, other_connections} = Map.pop(connections, program, MapSet.new())
  29. Enum.reduce(neighbours, MapSet.new([program]), &MapSet.union(&2, group(other_connections, &1)))
  30. end
  31. end
  32.  
  33. Day12.part1() |> IO.inspect
  34. Day12.part2() |> IO.inspect
Add Comment
Please, Sign In to add comment