Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Represents part of a wire.
- # One of x or y is an integer, and the other is a range.
- WirePart = Struct.new('WirePart', :x, :y, :direction) do
- def orientation
- x.is_a?(Range) ? :horizontal : :vertical
- end
- def horizontal?; orientation == :horizontal; end
- def vertical?; orientation == :vertical; end
- def intersection(other)
- if self.horizontal? && other.vertical?
- horiz = self
- vert = other
- elsif other.horizontal? && self.vertical?
- horiz = other
- vert = self
- else
- # Must be perpendicular to intersect
- return nil
- end
- # Don't count the origin
- return nil if vert.x == 0 && horiz.y == 0
- # Check ranges
- horiz.x.include?(vert.x) && vert.y.include?(horiz.y) \
- ? [vert.x, horiz.y]
- : nil
- end
- def part_length
- horizontal? \
- ? x.to_a.length
- : y.to_a.length
- end
- def wire_length
- part_length + (parent&.wire_length || 0)
- end
- end
- WIRES = []
- INTERSECTIONS = []
- def draw_wire(string)
- current_x = 0
- current_y = 0
- last_part = nil
- string.split(',').map do |movement|
- direction = movement[0]
- amount = movement[1..-1].to_i
- case direction
- when 'U'
- part = WirePart.new(current_x, current_y..(current_y + amount), direction)
- current_y += amount
- when 'D'
- part = WirePart.new(current_x, (current_y - amount)..current_y, direction)
- current_y -= amount
- when 'R'
- part = WirePart.new(current_x..(current_x + amount), current_y, direction)
- current_x += amount
- when 'L'
- part = WirePart.new((current_x - amount)..current_x, current_y, direction)
- current_x -= amount
- else
- raise 'unknown direction'
- end
- WIRES.each do |other_wire|
- other_wire.each do |other_part|
- isct = other_part.intersection(part)
- INTERSECTIONS << isct if isct
- end
- end
- last_part = part
- part
- end
- end
- File.read('input.txt').split("\n").each do |w|
- WIRES << draw_wire(w)
- end
- p INTERSECTIONS.map { |(x, y)| x.abs + y.abs }.sort.first
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement