Snippet

advent_of_code/2024_6.rb
Code:
# Advent of Code 2024, Day 6: Guard Gallivant

# https://adventofcode.com/2024/day/6

require_relative './helpers.rb'

def simulate(g)
  d, v = 0, find_grid(g, '^')[0]
  set_grid(g, v, d.to_s)
  while in_grid?(v, g)
    c = v.clone
    case d
      when 0; c.y -= 1; when 1; c.x += 1
      when 2; c.y += 1; when 3; c.x -= 1
    end
    if get_grid(g, c) =~ /\#|\O/
      d = (d + 1) % 4
    elsif get_grid(g, c) == d.to_s
      return nil # Loop!
    else
      v = c
      set_grid(g, v, d.to_s)
    end
  end
  g.flatten.select { |c| c =~ /\d/ }.size
end

def part_one(g)
  simulate(g).as { |c| c ? c : 'Loop!' }
end

def part_two(g)
  positions = []
  g.each_with_index do |r, y|
    r.each_with_index do |c, x|
      next unless c == '.'
      h, o = copy_grid(g), Point.new(x, y)
      set_grid(h, o, 'O')
      positions << o unless simulate(h)
    end
  end
  positions.size
end

def solve(data)
  data.map!(&:chomp).map! { |l| l.chars }
  draw_grid(data) if data.size < 20
  [part_one(copy_grid(data)), part_two(copy_grid(data))]
end

puts solve(get_dataset(year: 2024, day: 6, type: 'example'))
puts solve(get_dataset(year: 2024, day: 6, type: 'example_2'))
# puts solve(get_dataset(year: 2024, day: 6, type: 'input'))
Output:
....#.....
.........#
..........
..#.......
.......#..
..........
.#..^.....
........#.
#.........
......#...
41
6
.........
..#......
.......#.
..^......
.........
.#.......
......#..
.........
Loop!
54