חידה מקורית:
https://adventofcode.com/2018/day/5
פיתרון שלי בשפת רובי:
REACTOR_RE = Regexp.compile(('a'..'z').map { |c| "#{c}#{c.upcase}|#{c.upcase}#{c}" }.join('|'))
def length_after_reacting(input)
1 while input.gsub!(REACTOR_RE, '')
input.length
end
def regexp_for_specific_char(c)
Regexp.compile(c, Regexp::IGNORECASE)
end
res = {}
input = File.open(ARGV[0]).read.strip
('a'..'z').each do |c|
polymer = input.dup
remover = regexp_for_specific_char(c)
polymer.gsub!(remover, '')
res[c] = length_after_reacting(polymer)
end
puts res.values.min
ביטויים רגולאריים הם כלי שאני תמיד אוהב להשתמש בו, גם במקרים (כמו הפעם) שהביצועים לא היו הצד החזק בפיתרון. אם יש לכם (@Udi) רעיונות איך לגרום לקוד לרוץ יותר מהר ועדיין להשתמש בביטויים רגולאריים אשמח לשמוע.