r/adventofcode • • Dec 05 '18

SOLUTION MEGATHREAD -🎄- 2018 Day 5 Solutions -🎄-

--- Day 5: Alchemical Reduction ---


Post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag or whatever).

Note: The Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


Advent of Code: The Party Game!

Click here for rules

Please prefix your card submission with something like [Card] to make scanning the megathread easier. THANK YOU!

Card prompt: Day 5

Transcript:

On the fifth day of AoC / My true love sent to me / Five golden ___


This thread will be unlocked when there are a significant number of people on the leaderboard with gold stars for today's puzzle.

edit: Leaderboard capped, thread unlocked at 0:10:20!

31 Upvotes

515 comments sorted by

View all comments

1

u/charismotron Dec 05 '18

Ruby

https://github.com/chrismo/adventofcode2018/blob/master/day5/script.rb

def process(input)
  chars = input.chars
  idx = 0
  while idx < chars.length do
    idx = 0 if idx < 0
    char = chars[idx]
    next_char = chars[idx + 1]
    if char && next_char && char.downcase == next_char.downcase && char != next_char
      chars[idx] = nil
      chars[idx + 1] = nil
      chars.compact!
      idx -= 1
    else
      idx += 1
    end
  end
  chars.join
end

if __FILE__ == $0
  puts "Part 1"
  input = File.read('input.txt')
  output = process(input)
  puts "output length: #{output.length}"
  puts output

  puts "Part 2"
  res = {}
  ('a'..'z').each do |filter_char|
    print '.'
    filtered_input = input.dup.gsub(/#{filter_char}/i, "")
    output = process(filtered_input)
    res[filter_char] = output
  end
  puts
  shortest = res.min_by { |filter_char, out| out.length }
  p shortest
  puts shortest.last.length
end

Could be more elegant - the stack approach seems very ideal of course now that I see that. At least it runs not too slow (intermediate versions definitely bogged down):

$ time ruby script.rb 
Part 1
output length: 10384
Part 2
..........................
5412

real    0m8.799s
user    0m8.691s
sys     0m0.081s