From 8cd75cfd8601680af157a526302e0acd829515b5 Mon Sep 17 00:00:00 2001 From: Alexander Munch-Hansen Date: Sun, 10 Dec 2017 16:54:59 +0100 Subject: [PATCH] Day 9 --- my_parsing_nightmare.rb | 91 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 my_parsing_nightmare.rb diff --git a/my_parsing_nightmare.rb b/my_parsing_nightmare.rb new file mode 100644 index 0000000..22b8dcd --- /dev/null +++ b/my_parsing_nightmare.rb @@ -0,0 +1,91 @@ +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(: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, + "{,,,}" => 1, + "{{},{},{},{}}" => 1 + 2 + 2 + 2 + 2, + "{{},{},{},{}}" => 1 + 2 + 2 + 2 + 2, + "{{},{},{},{}}}" => 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