-
Notifications
You must be signed in to change notification settings - Fork 0
/
10a_solution.rb
56 lines (48 loc) · 1 KB
/
10a_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
49
50
51
52
53
54
55
56
input = File.read("./10input.txt").split("\n").map { |l| l.split("") }
$start_chars = %w|( [ { <|
$end_chars = %w|) ] } >|
class ParseError < StandardError
def initialize(illegal_char)
@illegal_char = illegal_char
end
attr_reader :illegal_char
end
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)
raise ParseError.new(char)
end
end
end
end
score = input.inject(0) do |a, line|
begin
try_parse(line)
a
rescue ParseError => e
case e.illegal_char
when ')'
a + 3
when ']'
a + 57
when '}'
a + 1197
when '>'
a + 25137
else
a
end
end
end
puts score