Created
December 10, 2021 18:08
-
-
Save sarahzrf/004352db625b231e4275e823f44ec32c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Corrupted < Exception | |
def initialize(got) | |
@got = got | |
end | |
attr_reader :got | |
end | |
class Parser | |
def initialize(text) | |
@text = text | |
@pos = 0 | |
end | |
def eof? | |
@pos >= @text.length | |
end | |
def peek | |
@text[@pos] or raise EOFError | |
end | |
def pop | |
char = peek | |
@pos += 1 | |
char | |
end | |
def unpop | |
@pos -= 1 | |
end | |
def expect(char) | |
nchar = pop | |
raise Corrupted.new(nchar) if nchar != char | |
end | |
def parse_chunk | |
case nchar = pop | |
when '(' | |
parse_chunk_body ')' | |
when '[' | |
parse_chunk_body ']' | |
when '{' | |
parse_chunk_body '}' | |
when '<' | |
parse_chunk_body '>' | |
else | |
unpop | |
raise Corrupted.new(nchar) | |
end | |
end | |
def parse_chunk_body(delim) | |
loop do | |
if peek == delim | |
pop | |
break | |
end | |
parse_chunk | |
end | |
end | |
end | |
Scoring = { | |
')' => 3, | |
']' => 57, | |
'}' => 1197, | |
'>' => 25137, | |
} | |
score = 0 | |
$<.each do |line| | |
p = Parser.new(line.chomp) | |
p.parse_chunk until p.eof? | |
rescue EOFError | |
rescue Corrupted => e | |
score += (Scoring[e.got] or 0) | |
end | |
print score | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment