Last active
December 6, 2024 06:18
-
-
Save imme5150/d51ab9746902aa1e2609bc7d1cbb3866 to your computer and use it in GitHub Desktop.
AoC 2024
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'set' | |
# copy a string to the clipboard | |
def cp(string = IRB.CurrentContext.last_value) | |
IO.popen('xclip -sel clip', 'w') { |f| f << string.to_s } | |
string | |
end | |
if ARGV[0] && ARGV[0][0].downcase == 't' | |
@lines = "....#..... | |
.........# | |
.......... | |
..#....... | |
.......#.. | |
.......... | |
.#..^..... | |
........#. | |
#......... | |
......#...".split("\n") | |
elsif ARGV[0] && ARGV[0][0].downcase == 'c' | |
@lines = `xclip -o`.split("\n") | |
else | |
@lines = File.readlines("input").map &:chomp | |
end | |
c = 0 | |
x = 0 | |
y = 0 | |
dir = 0 # up | |
@dirs = [ | |
[0,-1], # Up | |
[1,0], # Right | |
[0,1], # Down | |
[-1,0] # Left | |
] | |
@w = @lines.first.size | |
@h = @lines.size | |
@lines.each_with_index do |l, row| | |
if (x = l.index('^')) | |
y = row | |
l[x] = 'x' | |
break | |
end | |
end | |
@start_x = x | |
@start_y = y | |
loop do | |
nx = x + @dirs[dir][0] | |
ny = y + @dirs[dir][1] | |
break if nx < 0 || ny < 0 || nx >= @w || ny >= @h | |
if @lines[ny][nx] == '#' | |
# turn | |
dir = (dir + 1) % 4 | |
else | |
x = nx; | |
y = ny; | |
@lines[ny][nx] = 'x' | |
end | |
end | |
def is_loop?(lines) | |
x = @start_x | |
y = @start_y | |
dir = 0 | |
memo = [] | |
o_dir = nil | |
loop do | |
nx = x + @dirs[dir][0] | |
ny = y + @dirs[dir][1] | |
break if nx < 0 || ny < 0 || nx >= @w || ny >= @h | |
if lines[ny][nx] == '#' | |
desc = [x,y,dir] | |
return true if memo.include?(desc) | |
memo << desc | |
# turn | |
dir = (dir + 1) % 4 | |
elsif lines[ny][nx] == 'O' # obsticle | |
return true if o_dir == dir | |
o_dir ||= dir | |
dir = (dir + 1) % 4 | |
else | |
x = nx; | |
y = ny; | |
end | |
end | |
false | |
end | |
@lines.each_with_index do |l, row| | |
l.chars.each_with_index do |char, x|a | |
next if char != 'x' | |
lines = @lines.map(&:dup) | |
lines[row][x] = 'O' | |
c += 1 if is_loop?(lines) | |
end | |
end | |
# part 1 | |
puts cp @lines.sum {|l| l.count('x')} | |
# part 2 | |
puts cp c |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment