Created
December 10, 2021 18:12
-
-
Save sarahzrf/c85b3b4e544f070ae7302c9bb1fcbac2 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 | |
@completion = "" | |
end | |
attr_reader :completion | |
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 | |
begin | |
if peek == delim | |
pop | |
break | |
end | |
rescue EOFError | |
@completion << delim | |
raise | |
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 | |
print p.completion | |
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