Optimize day 5 solution.

This commit is contained in:
Danila Fedorin 2018-12-05 20:43:39 -08:00
parent 24c93c7a63
commit fde761d6af

33
day5.cr
View File

@ -2,30 +2,25 @@ require "./common.cr"
lines = File.read("day5_input").split("\n") lines = File.read("day5_input").split("\n")
struct Char
def inverse?(other)
return (other != self) && (other.downcase == self.downcase)
end
end
def react(string) def react(string)
string = string.chars stack = [] of Char
changed = true string.each_char do |char|
while changed last_char = stack.last?
changed = false if !last_char || !last_char.inverse? char
i = 0 stack << char
while i < string.size - 1 else
next_i = i + 1 stack.pop
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
end end
end end
return string return stack
end end
puts react(lines[0]).size puts react(lines[0]).size