AdventOfCode/my_parsing_nightmare.rb
2017-12-10 16:54:59 +01:00

92 lines
1.7 KiB
Ruby

require 'lex'
input = File.read("input_9.txt").strip
class MyLexer < Lex::Lexer
tokens(
:LBRACE,
:RBRACE,
:BANG,
:LGARB,
:RGARB,
:OTHER
)
# Regular expression rules for simple tokens
rule(:LBRACE, /\{/)
rule(:RBRACE, /}/)
rule(:BANG, /!/)
rule(:LGARB, /\</)
rule(:RGARB, /\>/)
rule(:OTHER, /./)
# A string containing ignored characters (spaces and tabs)
ignore " \t"
error do |lexer, token|
puts "Illegal character: #{value}"
end
end
LEXER = MyLexer.new
TESTS = { "{}" => 1,
"{{{}}}" => 1 + 2 + 3,
"{{},{}}" => 1 + 2 + 2,
"{{{},{},{{}}}}" => 1 + 2 + 3 + 3 + 3 + 4,
"{<a>,<a>,<a>,<a>}" => 1,
"{{<ab>},{<ab>},{<ab>},{<ab>}}" => 1 + 2 + 2 + 2 + 2,
"{{<!!>},{<!!>},{<!!>},{<!!>}}" => 1 + 2 + 2 + 2 + 2,
"{{<a!>},{<a!>},{<a!>},{<ab>}}}" => 1 + 2 }
def testings
TESTS.each do |test, expec|
res = parsing_lol test
if res == expec then
puts "[gj] #{test}"
else
puts "[fuck] #{test}\texpected #{expec}, got #{res}"
end
end
end
def parsing_lol str_in
lex = LEXER.lex str_in
garb = false
level = 0
sum = 0
garb_count = 0
begin
while elem = lex.next do
if not garb then
case elem.name
when :LBRACE
level += 1
sum += level
when :RBRACE
level -= 1
when :LGARB
garb = true
end
else
case elem.name
when :RGARB
garb = false
when :BANG
lex.next
else
garb_count += 1
end
end
end
rescue StopIteration
end
p sum
p garb_count
end
parsing_lol input