Advertisement
Guest User

AoC2024-6

a guest
Dec 6th, 2024
209
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.22 KB | Source Code | 0 0
  1. input = File.read("input.txt").split("\n")
  2. @width = input.size
  3. @height = input[0].size
  4. @grid = []
  5. @start = nil
  6. @dirs = [0-1i, 1+0i, 0+1i, -1+0i]
  7.  
  8. @width.times do |y|
  9.   @height.times do |x|
  10.     case input[y][x]
  11.     when ?#
  12.       @grid << Complex(x,y)
  13.     when ?^
  14.       @start = Complex(x,y)
  15.     end
  16.   end
  17. end
  18.  
  19. def inbounds?(pos)
  20.   pos.real.between?(0, @width-1) && pos.imag.between?(0, @height-1)
  21. end
  22.  
  23. def findPath
  24.   pos = @start
  25.   dir = 0
  26.   visited = Set[pos]
  27.   while inbounds?(pos) do
  28.     until @grid.include?(pos + @dirs[dir]) do
  29.       pos += @dirs[dir]
  30.       break unless inbounds?(pos)
  31.       visited << pos
  32.     end
  33.     dir = (dir+1) % 4
  34.   end
  35.   visited
  36. end
  37.  
  38. def hasCycle?(obstacle)
  39.   grid = @grid.dup << obstacle
  40.   pos = @start
  41.   dir = 0
  42.   visited = Set[[pos, dir]]
  43.  
  44.   while inbounds?(pos) do
  45.     until grid.include?(pos + @dirs[dir]) do
  46.       return true if visited.include?([pos + @dirs[dir], dir])
  47.       pos += @dirs[dir]
  48.       break unless inbounds?(pos)
  49.       visited << [pos, dir]
  50.     end
  51.     dir = (dir+1) % 4
  52.   end
  53.   false
  54. end
  55.  
  56. path = findPath
  57.  
  58. puts "Part 1: #{path.size}"
  59.  
  60. path.delete(@start)
  61.  
  62. obstacles = path.map{|p| hasCycle?(p)}.count(true)
  63.  
  64. puts "Part 2: #{obstacles}"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement