-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathday_10.ex
68 lines (58 loc) · 2.01 KB
/
day_10.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
63
64
65
66
67
68
defmodule AdventOfCode.Y2023.Day10 do
@moduledoc """
--- Day 10: Pipe Maze ---
Problem Link: https://adventofcode.com/2023/day/10
Difficulty: xl
Tags: graph graph-traversal needs-improvement not-fast-enough
"""
alias AdventOfCode.Algorithms.Grid
alias AdventOfCode.Helpers.{InputReader, Transformers}
def input, do: InputReader.read_from_file(2023, 10)
def run(input \\ input()) do
input = parse(input)
task_1 = Task.async(fn -> run_1(input) end)
task_2 = Task.async(fn -> run_2(input) end)
{Task.await(task_1, :infinity), Task.await(task_2, :infinity)}
end
defp run_1({_, circuit}), do: circuit |> Enum.count() |> div(2)
defp run_2({graph, circuit}) do
graph
|> Graph.vertices()
|> Stream.reject(&(&1 in circuit))
|> Stream.map(&Topo.contains?(%Geo.Polygon{coordinates: [circuit]}, &1))
|> Enum.count(&Function.identity/1)
end
def parse(data \\ input()) do
data
|> Transformers.lines()
|> Enum.map(&String.graphemes/1)
|> Grid.grid2d()
|> then(fn grid ->
graph = to_graph(grid)
{start, _} = Enum.find(grid, fn {_, tile} -> tile == "S" end)
{graph, circuit_nodes(graph, start)}
end)
end
defp to_graph(grid) do
for {{x, y}, tile} <- grid, reduce: Graph.new() do
acc ->
case connected({x, y}, tile) do
{n1, n2} -> acc |> Graph.add_edge({x, y}, n1) |> Graph.add_edge({x, y}, n2)
nil -> acc
end
end
end
defp connected({x, y}, "|"), do: {{x - 1, y}, {x + 1, y}}
defp connected({x, y}, "-"), do: {{x, y - 1}, {x, y + 1}}
defp connected({x, y}, "L"), do: {{x - 1, y}, {x, y + 1}}
defp connected({x, y}, "J"), do: {{x - 1, y}, {x, y - 1}}
defp connected({x, y}, "7"), do: {{x, y - 1}, {x + 1, y}}
defp connected({x, y}, "F"), do: {{x, y + 1}, {x + 1, y}}
defp connected(_, _), do: nil
defp circuit_nodes(graph, start) do
graph
|> Graph.in_neighbors(start)
|> Enum.reduce(graph, &Graph.add_edge(&2, start, &1))
|> Graph.reachable_neighbors([start])
end
end