Optimize day 5 solution.
This commit is contained in:
parent
24c93c7a63
commit
fde761d6af
31
day5.cr
31
day5.cr
|
@ -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
|
|
||||||
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
|
else
|
||||||
i += 1
|
stack.pop
|
||||||
end
|
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
return string
|
return stack
|
||||||
end
|
end
|
||||||
|
|
||||||
puts react(lines[0]).size
|
puts react(lines[0]).size
|
||||||
|
|
Loading…
Reference in New Issue
Block a user