Code for the Advent of Code event
aoc advent-of-code

Clean up Ruby for 2024 day 15 some more

+29 -30
+29 -30
src/2024/15/solve.rb
··· 1 1 #!/usr/bin/env ruby 2 2 # frozen_string_literal: true 3 3 4 - require 'matrix' 4 + require 'bundler/setup' 5 + require 'aoc/point' 6 + 7 + P = AoC::Point2 8 + 9 + LEFT = P[-1, 0] 10 + DOWN = P[0, 1] 11 + RIGHT = P[1, 0] 12 + UP = P[0, -1] 5 13 6 14 DIRS = { 7 - ?< => Vector[-1, 0], 8 - ?v => Vector[0, 1], 9 - ?> => Vector[1, 0], 10 - ?^ => Vector[0, -1] 15 + ?< => LEFT, 16 + ?v => DOWN, 17 + ?> => RIGHT, 18 + ?^ => UP 11 19 }.freeze 12 - 13 - LEFT = Vector[-1, 0] 14 - DOWN = Vector[0, 1] 15 - RIGHT = Vector[1, 0] 16 - UP = Vector[0, -1] 17 20 18 21 CELL_MATES = { 19 22 ?. => ?., ··· 22 25 ?[ => ?] 23 26 }.freeze 24 27 25 - def display(grid, width, height) 26 - puts '=' * width 27 - height.times do |y| 28 - width.times do |x| 29 - print ' ' if grid[Vector[x, y]].nil? 30 - print grid[Vector[x, y]] 28 + def display(grid) 29 + $width ||= grid.keys.map(&:x).max + 1 30 + $height ||= grid.keys.map(&:y).max + 1 31 + puts '=' * $width 32 + $height.times do |y| 33 + $width.times do |x| 34 + print ' ' if grid[P[x, y]].nil? 35 + print grid[P[x, y]] 31 36 end 32 37 puts 33 38 end 34 - puts '=' * width 39 + puts '=' * $width 35 40 end 36 41 37 42 map_str, move_str = ARGF.read.split "\n\n" 38 43 39 44 grid = map_str.lines.flat_map.with_index { |line, y| 40 45 line.chomp.chars.map.with_index { |c, x| 41 - [Vector[x, y], c] 46 + [P[x, y], c] 42 47 } 43 48 }.to_h 44 49 45 50 grid2 = grid.flat_map { |k, v| 46 - new_k = Vector[k[0] * 2, k[1]] 47 - first = v == ?O ? ?[ : v 48 - second = CELL_MATES[first] 49 - [[new_k, first], [new_k + Vector[1, 0], second]] 51 + new_k = P[k.x * 2, k.y] 52 + cell = v == ?O ? ?[ : v 53 + [[new_k, cell], [new_k + P[1, 0], CELL_MATES[cell]]] 50 54 }.to_h 51 - 52 - WIDTH = grid.keys.map { _1[0] }.max + 1 53 - HEIGHT = grid.keys.map { _1[1] }.max + 1 54 - WIDTH2 = grid2.keys.map { _1[0] }.max + 1 55 - HEIGHT2 = grid2.keys.map { _1[1] }.max + 1 56 55 57 56 START = grid.find { |_, v| v == ?@ }.first 58 57 START2 = grid2.find { |_, v| v == ?@ }.first ··· 99 98 end 100 99 101 100 def move2(grid, pos, dir) 102 - return move_vertical(grid, [pos], dir)[0] if dir[0].zero? 101 + return move_vertical(grid, [pos], dir)[0] if dir.x.zero? 103 102 move(grid, pos, dir) 104 103 end 105 104 ··· 111 110 pos2 = move2(grid2, pos2, m) 112 111 end 113 112 114 - puts grid.filter_map { |p, v| v == ?O ? p : nil }.sum { (100 * _1[1]) + _1[0] } 115 - puts grid2.filter_map { |p, v| v == ?[ ? p : nil }.sum { (100 * _1[1]) + _1[0] } 113 + puts grid.filter_map { |p, v| v == ?O ? p : nil }.sum { (100 * _1.y) + _1.x } 114 + puts grid2.filter_map { |p, v| v == ?[ ? p : nil }.sum { (100 * _1.y) + _1.x }