|
| 1 | +class Day05 |
| 2 | + def self.go |
| 3 | + day = new |
| 4 | + puts "Part 1: #{day.part1}" |
| 5 | + puts "Part 2: #{day.part2}" |
| 6 | + end |
| 7 | + |
| 8 | + def initialize(input=nil) |
| 9 | + @input = input || real_input |
| 10 | + @stacks = parse_stacks |
| 11 | + @moves = parse_moves |
| 12 | + end |
| 13 | + |
| 14 | + # @example |
| 15 | + # day.part1 => "CMZ" |
| 16 | + def part1 |
| 17 | + @moves |
| 18 | + .each { |step| |
| 19 | + step[:quantity].times { |
| 20 | + @stacks[step[:to]].push( @stacks[step[:from]].pop) |
| 21 | + } |
| 22 | + } |
| 23 | + |
| 24 | + @stacks |
| 25 | + .values |
| 26 | + .map(&:last) |
| 27 | + .join("") |
| 28 | + end |
| 29 | + |
| 30 | + def part2 |
| 31 | + end |
| 32 | + |
| 33 | + # @example |
| 34 | + # day.parse_stacks => EXAMPLE_STACK_START |
| 35 | + def parse_stacks |
| 36 | + stacks_input, _ = @input.split("\n\n") |
| 37 | + |
| 38 | + stacks_input |
| 39 | + .split("\n") |
| 40 | + .reverse |
| 41 | + .map(&:chars) |
| 42 | + .transpose |
| 43 | + .select{ |stack| stack[0] != " " } |
| 44 | + .each_with_object({}) { |stack_in, stacks| |
| 45 | + stack_no = stack_in.shift |
| 46 | + stacks[stack_no] = stack_in.select{|crate| crate != " "} |
| 47 | + } |
| 48 | + end |
| 49 | + |
| 50 | + # @example |
| 51 | + # day.parse_moves => EXAMPLE_MOVES |
| 52 | + def parse_moves |
| 53 | + _, moves_input = @input.split("\n\n") |
| 54 | + |
| 55 | + moves_input |
| 56 | + .split("\n") |
| 57 | + .each_with_object([]) { |line, moves| |
| 58 | + line.match(/move (\d+) from (\d+) to (\d+)/) { |matchdata| |
| 59 | + moves << { quantity: matchdata[1].to_i, from: matchdata[2], to: matchdata[3] } |
| 60 | + } |
| 61 | + } |
| 62 | + end |
| 63 | + |
| 64 | + def real_input |
| 65 | + File.read('../inputs/day05-input.txt') |
| 66 | + end |
| 67 | + |
| 68 | + EXAMPLE_STACK_START = { |
| 69 | + "1" => %w[Z N], |
| 70 | + "2" => %w[M C D], |
| 71 | + "3" => %w[P], |
| 72 | + } |
| 73 | + EXAMPLE_MOVES = [ |
| 74 | + { quantity: 1, from: "2", to: "1" }, |
| 75 | + { quantity: 3, from: "1", to: "3" }, |
| 76 | + { quantity: 2, from: "2", to: "1" }, |
| 77 | + { quantity: 1, from: "1", to: "2" }, |
| 78 | + ] |
| 79 | + EXAMPLE_INPUT = <<~INPUT |
| 80 | + [D] |
| 81 | + [N] [C] |
| 82 | + [Z] [M] [P] |
| 83 | + 1 2 3 |
| 84 | + |
| 85 | + move 1 from 2 to 1 |
| 86 | + move 3 from 1 to 3 |
| 87 | + move 2 from 2 to 1 |
| 88 | + move 1 from 1 to 2 |
| 89 | + INPUT |
| 90 | +end |
0 commit comments