5.rb 838 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. @input = File.read("5.input").split("\n")
  2. def stacks()
  3. return @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}
  4. end
  5. @instrs = @input.filter{|line| line.include?("move")}.map{|line| line.split(/[a-z ]+/)}
  6. def part1()
  7. stacks = stacks()
  8. @instrs.each do |inst|
  9. (_, cnt, from, to) = inst.map{|i| i.to_i}
  10. (1..cnt).each do |_|
  11. box = stacks[from - 1].pop()
  12. stacks[to - 1].append(box)
  13. end
  14. end
  15. puts stacks.map{|s| s[-1]}.join()
  16. end
  17. def part2()
  18. stacks = stacks()
  19. @instrs.each do |inst|
  20. (_, cnt, from, to) = inst.map{|i| i.to_i}
  21. boxes = stacks[from - 1].pop(cnt)
  22. stacks[to - 1] = stacks[to - 1].concat(boxes)
  23. end
  24. puts stacks.map{|s| s[-1]}.join()
  25. end
  26. part1()
  27. part2()