-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathday_09.ex
56 lines (45 loc) · 1.46 KB
/
day_09.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
defmodule AdventOfCode.Y2015.Day09 do
@moduledoc """
--- Day 9: All in a Single Night ---
Problem Link: https://adventofcode.com/2015/day/9
Difficulty: s
Tags: graph routing
"""
alias AdventOfCode.Helpers.{InputReader, Transformers}
def input, do: InputReader.read_from_file(2015, 9)
def run(input \\ input()) do
input = parse(input)
{run_1(input), run_2(input)}
end
def run_1(input), do: input |> travel_all(&Enum.min/1)
def run_2(input), do: input |> travel_all(&Enum.max/1)
def parse(data \\ input()) do
data
|> Transformers.lines()
|> Enum.map(fn route ->
~r/(\w+) to (\w+) = (\d+)/
|> Regex.run(route, capture: :all_but_first)
|> then(&List.to_tuple/1)
end)
|> to_graph()
end
defp to_graph(data) do
routes =
data
|> Enum.flat_map(fn {c1, c2, dist} ->
[{{c1, c2}, String.to_integer(dist)}, {{c2, c1}, String.to_integer(dist)}]
end)
|> Map.new()
cities = routes |> Map.keys() |> Enum.flat_map(&Tuple.to_list/1) |> MapSet.new()
{cities, routes}
end
defp travel_all({cities, routes}, min_max_fn),
do: min_max_fn.(Enum.map(cities, &travel(&1, routes, cities, 0, min_max_fn)))
defp travel(city, routes, cities, distance, min_max_fn) do
cities = MapSet.delete(cities, city)
(Enum.empty?(cities) && distance) ||
cities
|> Enum.map(&travel(&1, routes, cities, distance + routes[{city, &1}], min_max_fn))
|> min_max_fn.()
end
end