-
Notifications
You must be signed in to change notification settings - Fork 0
/
10b_solution.rb
48 lines (40 loc) · 1.03 KB
/
10b_solution.rb
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
input = File.read("./10input.txt").split("\n").map { |l| l.split("") }
$start_chars = %w|( [ { <|
$end_chars = %w|) ] } >|
def mismatch?(start_char, end_char)
(start_char == '(' && end_char != ')') ||
(start_char == '[' && end_char != ']') ||
(start_char == '{' && end_char != '}') ||
(start_char == '<' && end_char != '>')
end
def try_parse(chars)
stack = []
chars.each do |char|
if $start_chars.include?(char)
stack.push char
elsif $end_chars.include?(char)
start = stack.pop
if mismatch?(start, char)
return 0 # ignore corrupted lines
end
end
end
stack.reverse.inject(0) do |a, e|
value = case e
when '('
1
when '['
2
when '{'
3
when '<'
4
else
raise "illegal state"
end
a * 5 + value
end
end
scores = input.map { |line| try_parse(line) }.reject { |s| s == 0 }
middle_score = scores.sort[(scores.size+1)/2-1]
puts middle_score