5.rb 739 B

123456789101112131415161718192021222324252627
  1. @input = File.read("5.input").split("\n")
  2. @instrs = @input.filter{|line| line.include?("move")}.map{|line| line.split(/[a-z ]+/)}
  3. def run_part
  4. stacks = @input.filter {|line| line.include?("[")}.map{|line| line.chars.each_slice(4).to_a.map{|block| block[1]}}.transpose.map{|stack| stack.filter{|box| box != " "}.reverse}
  5. @instrs.each do |inst|
  6. (_, cnt, from, to) = inst.map{|i| i.to_i}
  7. yield stacks, cnt, from - 1, to - 1
  8. end
  9. puts stacks.map{|s| s[-1]}.join()
  10. end
  11. # Part 1
  12. run_part do |stacks, cnt, from, to|
  13. (1..cnt).each do |_|
  14. box = stacks[from].pop()
  15. stacks[to].append(box)
  16. end
  17. end
  18. # Part 2
  19. run_part do |stacks, cnt, from, to|
  20. boxes = stacks[from].pop(cnt)
  21. stacks[to] = stacks[to].concat(boxes)
  22. end