From fde761d6af58266f1f18c28571ba76bd02e14897 Mon Sep 17 00:00:00 2001 From: Danila Fedorin Date: Wed, 5 Dec 2018 20:43:39 -0800 Subject: [PATCH] Optimize day 5 solution. --- day5.cr | 33 ++++++++++++++------------------- 1 file changed, 14 insertions(+), 19 deletions(-) diff --git a/day5.cr b/day5.cr index 3dcd7ba..f2023f9 100644 --- a/day5.cr +++ b/day5.cr @@ -2,30 +2,25 @@ require "./common.cr" lines = File.read("day5_input").split("\n") +struct Char + def inverse?(other) + return (other != self) && (other.downcase == self.downcase) + end +end + def react(string) - string = string.chars + stack = [] of Char - changed = true - while changed - changed = false - i = 0 - while i < string.size - 1 - next_i = i + 1 - if string[i] != string[next_i] && - string[i].downcase == string[next_i].downcase - string.delete_at i - string.delete_at i - - i -= 1 - i = 0 if i < 0 - changed = true - else - i += 1 - end + string.each_char do |char| + last_char = stack.last? + if !last_char || !last_char.inverse? char + stack << char + else + stack.pop end end - return string + return stack end puts react(lines[0]).size