Guest User

Untitled

a guest
Dec 16th, 2023
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.88 KB | None | 0 0
  1. layout = File.read('input.txt').split("\n").map{|l| l.chars}
  2.  
  3. def beam(level, map, row, col, direction, visited)
  4.   # encode all the movements, e.g., going right and encounter '.' => just keep going right
  5.   movements = {
  6.     right:  {'.': :right,  '/': :up,     '\\': :down,  '|': [:up, :down], '-': :right},
  7.     left:   {'.': :left,   '/': :down,   '\\': :up,    '|': [:up, :down], '-': :left},
  8.     up:     {'.': :up,     '/': :right,  '\\': :left,  '|': :up,          '-': [:left, :right]},
  9.     down:   {'.': :down,   '/': :left,   '\\': :right, '|': :down,        '-': [:left, :right]},
  10.   }
  11.  
  12.   while col >= 0 and col < map[0].length and row >= 0 and row < map.length
  13.     # already passed this point going in this direction,
  14.     # no need to push on
  15.     break if visited.include?([row, col, direction])
  16.     visited.add [row, col, direction]
  17.  
  18.     direction = movements[direction][map[row][col].to_sym]
  19.     case direction
  20.     when :up
  21.       row = row-1
  22.     when :down
  23.       row = row+1
  24.     when :left
  25.       col = col-1
  26.     when :right
  27.       col = col+1
  28.     when [:up, :down]
  29.       # go down plus new beam up
  30.       beam(level+1, map, row-1, col, :up, visited)
  31.       direction = :down
  32.       row = row+1
  33.     when [:left, :right]
  34.       # go right plus new beam left
  35.       beam(level+1, map, row, col-1, :left, visited)
  36.       direction = :right
  37.       col = col+1
  38.     end
  39.   end
  40.   return visited.map{|r,c,d| [r,c]}.uniq.count if (level == 0)
  41. end
  42.  
  43. # part 1
  44. p beam(0, layout, 0, 0, :right, Set.new)
  45.  
  46. # part 2 fast enough to just brute force it
  47. rows = 0..layout.length - 1
  48. cols = 0..layout[0].length - 1
  49. p [
  50.   rows.map{|r| beam(0, layout, r, cols.first, :right, Set.new)}.max,
  51.   rows.map{|r| beam(0, layout, r, cols.last, :left, Set.new)}.max,
  52.   cols.map{|c| beam(0, layout, rows.first, c, :down, Set.new)}.max,
  53.   cols.map{|c| beam(0, layout, rows.last, c, :up, Set.new)}.max
  54. ].max
  55.  
Advertisement
Add Comment
Please, Sign In to add comment