Skip to content

Instantly share code, notes, and snippets.

@carlwiedemann
Created December 6, 2024 19:23
Show Gist options
  • Save carlwiedemann/16988e5eb859be1b6b33299620165191 to your computer and use it in GitHub Desktop.
Save carlwiedemann/16988e5eb859be1b6b33299620165191 to your computer and use it in GitHub Desktop.
Advent of Code 2024 day006.rb
require_relative "main"
module Day006
INPUT = File.read('INPUT.txt')
grid = INPUT.to_grid
NORTH = V[0, -1]
SOUTH = V[0, 1]
WEST = V[-1, 0]
EAST = V[1, 0]
BLOCK = '#'
EMPTY = '.'
ROTATION = {
NORTH => EAST,
EAST => SOUTH,
SOUTH => WEST,
WEST => NORTH
}
##########
# Part 1 #
##########
history = {}
cursor, dir = grid.find('^'), NORTH
loop do
loop do
potential = cursor + dir
if grid.get_value(potential) != BLOCK
history[potential] ||= [cursor, dir]
cursor = potential
break
end
dir = ROTATION[dir]
end
break unless grid.in_bounds?(cursor)
end
answer1 = history.keys.count
pp answer1
##########
# Part 2 #
##########
answer2 = history.keys[1...-1].sum do |v|
grid.set_value(v, BLOCK)
visited = Hash.new { |h, k| h[k] = 0 }
cursor, dir = history[v]
cycle = false
loop do
visited[cursor] += 1
break if (cycle = visited[cursor] > 4)
loop do
potential = cursor + dir
if grid.get_value(potential) != BLOCK
cursor = potential
break
end
dir = ROTATION[dir]
end
break unless grid.in_bounds?(cursor)
end
grid.set_value(v, EMPTY)
cycle ? 1 : 0
end
pp answer2
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment