-
Notifications
You must be signed in to change notification settings - Fork 3
/
day03.ex
86 lines (73 loc) · 1.72 KB
/
day03.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
defmodule Elixir2020.Day03.GridWithMax do
alias Elixir2020.Day03.GridWithMax
defstruct [
:grid,
:max_x,
:max_y
]
def new(grid) when is_map(grid) do
{max_x, _} = grid |> Map.keys() |> Enum.max_by(fn {x, _y} -> x end)
{_, max_y} = grid |> Map.keys() |> Enum.max_by(fn {_x, y} -> y end)
%GridWithMax{
grid: grid,
max_x: max_x,
max_y: max_y
}
end
end
defmodule Elixir2020.Day03 do
alias Elixir2020.Day03.GridWithMax
def parse(filename) do
File.stream!(filename)
|> Enum.map(&String.trim/1)
|> parse_lines()
end
def parse_lines(lines) do
lines
|> Enum.zip(0..9999)
|> Enum.flat_map(&parse_line/1)
|> Map.new()
|> GridWithMax.new()
end
def parse_line({maze_string, row}) do
maze_string
|> String.graphemes()
|> Enum.zip(0..9999)
|> Enum.map(fn {char, col} ->
{{col, row}, char}
end)
end
def grid_at(grid, {x, y}) do
if y > grid.max_y do
:below_field
else
x = rem(x, grid.max_x + 1)
grid.grid |> Map.get({x, y})
end
end
def solve_slope(grid, {dx, dy}), do: do_solve_slope(grid, {dx, dy}, {0, 0}, 0)
def do_solve_slope(grid, {dx, dy}, {x, y}, trees_hit) do
case grid_at(grid, {x, y}) do
:below_field -> trees_hit
"#" -> do_solve_slope(grid, {dx, dy}, {x + dx, y + dy}, trees_hit + 1)
_ -> do_solve_slope(grid, {dx, dy}, {x + dx, y + dy}, trees_hit)
end
end
def part1(filename) do
parse(filename)
|> solve_slope({3, 1})
end
def part2(filename) do
grid = parse(filename)
[
{1, 1},
{3, 1},
{5, 1},
{7, 1},
{1, 2}
]
|> Enum.reduce(1, fn slope, acc ->
acc * solve_slope(grid, slope)
end)
end
end