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")
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