Created
December 6, 2019 11:53
-
-
Save bossek/98b7aff0dbe7d5e924365a24c091cac0 to your computer and use it in GitHub Desktop.
Advent of Code 2019 - Day 06
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 Day06 do | |
| def part01 do | |
| sum_tree(data()) | |
| end | |
| def part02 do | |
| distance(data(), "YOU", "SAN") | |
| end | |
| defp data do | |
| "data/day06.txt" | |
| |> File.read!() | |
| |> parse() | |
| |> build_tree() | |
| end | |
| defp distance(tree, from, to) do | |
| dfrom = Map.new(distances(from, tree)) | |
| dto = Map.new(distances(to, tree)) | |
| both = MapSet.intersection(MapSet.new(Map.keys(dfrom)), MapSet.new(Map.keys(dto))) | |
| Enum.map(both, &(dfrom[&1] + dto[&1] - 2)) |> Enum.min() | |
| end | |
| defp sum_tree(tree) do | |
| tree | |
| |> Map.keys() | |
| |> Enum.map(&distances(&1, tree)) | |
| |> Enum.map(&Enum.at(&1, -1)) | |
| |> Enum.map(&elem(&1, 1)) | |
| |> Enum.sum() | |
| end | |
| defp distances(node, distance \\ 0, tree) do | |
| if node == nil, do: [], else: [{node, distance} | distances(tree[node], distance + 1, tree)] | |
| end | |
| defp build_tree(data) do | |
| Enum.into(data, %{}, fn [from, to] -> {to, from} end) | |
| end | |
| defp parse(data) do | |
| data | |
| |> String.split("\n", trim: true) | |
| |> Enum.map(&String.split(&1, ")")) | |
| end | |
| end | |
| IO.inspect(Day06.part01(), label: "part 1") | |
| IO.inspect(Day06.part02(), label: "part 2") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment