Advertisement
Guest User

Untitled

a guest
Dec 9th, 2019
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.08 KB | None | 0 0
  1. # Represents part of a wire.
  2. # One of x or y is an integer, and the other is a range.
  3. WirePart = Struct.new('WirePart', :x, :y, :direction) do
  4. def orientation
  5. x.is_a?(Range) ? :horizontal : :vertical
  6. end
  7.  
  8. def horizontal?; orientation == :horizontal; end
  9. def vertical?; orientation == :vertical; end
  10.  
  11. def intersection(other)
  12. if self.horizontal? && other.vertical?
  13. horiz = self
  14. vert = other
  15. elsif other.horizontal? && self.vertical?
  16. horiz = other
  17. vert = self
  18. else
  19. # Must be perpendicular to intersect
  20. return nil
  21. end
  22.  
  23. # Don't count the origin
  24. return nil if vert.x == 0 && horiz.y == 0
  25.  
  26. # Check ranges
  27. horiz.x.include?(vert.x) && vert.y.include?(horiz.y) \
  28. ? [vert.x, horiz.y]
  29. : nil
  30. end
  31.  
  32. def part_length
  33. horizontal? \
  34. ? x.to_a.length
  35. : y.to_a.length
  36. end
  37.  
  38. def wire_length
  39. part_length + (parent&.wire_length || 0)
  40. end
  41. end
  42.  
  43. WIRES = []
  44. INTERSECTIONS = []
  45.  
  46. def draw_wire(string)
  47. current_x = 0
  48. current_y = 0
  49. last_part = nil
  50.  
  51. string.split(',').map do |movement|
  52. direction = movement[0]
  53. amount = movement[1..-1].to_i
  54.  
  55. case direction
  56. when 'U'
  57. part = WirePart.new(current_x, current_y..(current_y + amount), direction)
  58. current_y += amount
  59. when 'D'
  60. part = WirePart.new(current_x, (current_y - amount)..current_y, direction)
  61. current_y -= amount
  62. when 'R'
  63. part = WirePart.new(current_x..(current_x + amount), current_y, direction)
  64. current_x += amount
  65. when 'L'
  66. part = WirePart.new((current_x - amount)..current_x, current_y, direction)
  67. current_x -= amount
  68. else
  69. raise 'unknown direction'
  70. end
  71.  
  72. WIRES.each do |other_wire|
  73. other_wire.each do |other_part|
  74. isct = other_part.intersection(part)
  75. INTERSECTIONS << isct if isct
  76. end
  77. end
  78.  
  79. last_part = part
  80. part
  81. end
  82. end
  83.  
  84. File.read('input.txt').split("\n").each do |w|
  85. WIRES << draw_wire(w)
  86. end
  87.  
  88. p INTERSECTIONS.map { |(x, y)| x.abs + y.abs }.sort.first
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement