-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathday_09.ex
100 lines (76 loc) · 2.59 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
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
defmodule AdventOfCode.Y2017.Day09 do
@moduledoc """
--- Day 9: Stream Processing ---
Problem Link: https://adventofcode.com/2017/day/9
Difficulty: s
Tags: fsm
"""
alias AdventOfCode.Helpers.InputReader
def input, do: InputReader.read_from_file(2017, 9)
def run(input \\ input()) do
input = String.graphemes(input)
{run_1(input), run_2(input)}
end
def run_1(input), do: process_groups(input)
def run_2(input), do: process_garbages(input)
def process_groups(data) do
data
|> groups(1, false, false, [])
|> Enum.sum()
end
def process_garbages(data) do
data
|> garbages(0, false, false, [])
|> Enum.sum()
end
defp groups([], _, _, _, groups), do: groups
defp groups(["{" | data], level, false, false, groups) do
groups(data, level + 1, false, false, [level | groups])
end
defp groups(["}" | data], level, false, false, groups) do
groups(data, level - 1, false, false, groups)
end
defp groups(["," | data], level, false, false, groups) do
groups(data, level, false, false, groups)
end
defp groups(["<" | data], level, false, false, groups) do
groups(data, level, true, false, groups)
end
defp groups(["!" | data], level, true, false, groups) do
groups(data, level, true, true, groups)
end
defp groups([_ | data], level, true, true, groups) do
groups(data, level, true, false, groups)
end
defp groups([">" | data], level, true, false, groups) do
groups(data, level, false, false, groups)
end
defp groups([_ | data], level, true, false, groups) do
groups(data, level, true, false, groups)
end
defp garbages([], _, _, _, garbages), do: garbages
defp garbages(["{" | data], count, false, false, garbages) do
garbages(data, count, false, false, garbages)
end
defp garbages(["}" | data], count, false, false, garbages) do
garbages(data, count, false, false, garbages)
end
defp garbages(["," | data], count, false, false, garbages) do
garbages(data, count, false, false, garbages)
end
defp garbages(["<" | data], count, false, false, garbages) do
garbages(data, count, true, false, garbages)
end
defp garbages(["!" | data], count, true, false, garbages) do
garbages(data, count, true, true, garbages)
end
defp garbages([_ | data], count, true, true, garbages) do
garbages(data, count, true, false, garbages)
end
defp garbages([">" | data], count, true, false, garbages) do
garbages(data, 0, false, false, [count | garbages])
end
defp garbages([_ | data], count, true, false, garbages) do
garbages(data, count + 1, true, false, garbages)
end
end