-
Notifications
You must be signed in to change notification settings - Fork 4
/
day_06.ex
62 lines (53 loc) · 1.31 KB
/
day_06.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
defmodule AdventOfCode.Y2019.Day06 do
@moduledoc """
--- Day 6: Universal Orbit Map ---
Problem Link: https://adventofcode.com/2019/day/6
Difficulty: xs
Tags: graph routing
"""
alias AdventOfCode.Helpers.{InputReader, Transformers}
def input, do: InputReader.read_from_file(2019, 6)
def run(input \\ input()) do
input = parse(input)
{run_1(input), run_2(input)}
end
def run_1(input) do
input
|> to_graph(:digraph.new([:acyclic]))
|> count_orbits()
end
def run_2(input) do
input
|> to_graph(:digraph.new())
|> count_orbital_transfers()
end
def parse(data) do
data |> Transformers.lines() |> Enum.map(&String.split(&1, ")"))
end
defp to_graph(data, graph) do
data
|> Enum.each(fn [a, b] ->
:digraph.add_vertex(graph, a)
:digraph.add_vertex(graph, b)
:digraph.add_edge(graph, b, a)
:digraph.add_edge(graph, a, b)
end)
graph
end
defp count_orbits(graph) do
graph
|> :digraph.vertices()
|> Stream.map(fn vertex ->
:digraph.get_path(graph, vertex, "COM") || []
end)
|> Stream.map(fn path -> length(path) - 1 end)
|> Enum.sum()
|> Kernel.+(1)
end
defp count_orbital_transfers(graph) do
graph
|> :digraph.get_short_path("YOU", "SAN")
|> Enum.count()
|> Kernel.-(3)
end
end