-
Notifications
You must be signed in to change notification settings - Fork 0
/
10.jl
109 lines (97 loc) · 2.16 KB
/
10.jl
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
101
102
103
104
105
106
107
108
109
using DataStructures
using Formatting
import Statistics
slurp_file(filename) = collect.(readlines(filename))
parens = Dict(
'{' => '}',
'<' => '>',
'(' => ')',
'[' => ']'
)
opening_chars = Set(keys(parens))
closing_chars = Set(values(parens))
function first_error(line)
opened = Stack{Char}()
for char in line
if isempty(opened)
if char in closing_chars
return char
else
push!(opened, char)
end
else
opening_char = first(opened)
if char == parens[opening_char]
pop!(opened)
elseif char in closing_chars
return char
else
push!(opened, char)
end
end
end
return ' '
end
scores = Dict(
')' => 3,
']' => 57,
'}' => 1197,
'>' => 25137,
' ' => 0
)
function solve1(filename)
reduce(+, (c->scores[c]).(first_error.(slurp_file(filename))))
end
solve1("10eg.txt")
solve1("10.txt")
function get_closing(line)
opened = Stack{Char}()
for char in line
if isempty(opened)
if char in closing_chars
return char
else
push!(opened, char)
end
else
opening_char = first(opened)
if char == parens[opening_char]
pop!(opened)
elseif char in closing_chars
return char
else
push!(opened, char)
end
end
end
result = []
for c in opened
push!(result, parens[c])
end
result
end
scores2 = Dict(
')' => 1,
']' => 2,
'}' => 3,
'>' => 4
)
function score2(chars)
result = 0
for char in chars
result *= 5
result += scores2[char]
end
result
end
score2(collect("}}]])})]")) == 288957
function solve2(filename)
lines = [line for line in slurp_file(filename) if first_error(line) == ' ']
println(length(lines))
scores = score2.(get_closing.(lines))
@show scores
sorted = sort(scores)
Statistics.median(sorted)
end
solve2("10eg.txt") == 288957
format(solve2("10.txt"))