Advertisement
aexvir

rope simluation thingy

Dec 9th, 2022 (edited)
862
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.72 KB | Source Code | 0 0
  1. from pathlib import Path
  2.    
  3. def parse(line):
  4.     direction, amount = line.split(" ")
  5.     return direction.lower(), int(amount)
  6.  
  7. offsets = {"u": (0, 1), "d": (0, -1), "l": (-1, 0), "r": (1, 0)}
  8.  
  9.  
  10. class Coord:
  11.     x, y = 0, 0
  12.    
  13.     def __init__(self, x=0, y=0):
  14.         self.x, self.y = x, y
  15.    
  16.     def move(self, tx, ty):
  17.         self.x += tx
  18.         self.y += ty
  19.        
  20.     def carry(self, other):
  21.         if abs(self.x - other.x) > 0:
  22.             other.x += (1 if self.x > other.x else -1)
  23.  
  24.         if abs(self.y - other.y) > 0:
  25.             other.y += (1 if self.y > other.y else -1)
  26.            
  27.         return Coord(other.x, other.y)
  28.        
  29.     def distance(self, other):
  30.         return max(abs(self.x - other.x), abs(self.y - other.y))
  31.  
  32.  
  33. class Rope:
  34.     head = Coord(0,0)
  35.     knots = []
  36.     visited = {(0,0)}
  37.    
  38.     def __init__(self, knots=2):
  39.         # head is a knot
  40.         for n in range(knots-1):
  41.             self.knots.append(Coord(0,0))
  42.    
  43.     def move(self, direction, amount):
  44.         for _ in range(amount):
  45.             self.head.move(*offsets[direction])
  46.            
  47.             # each knot "carries" the next one
  48.             current = self.head
  49.             for knot in self.knots:
  50.                 while current.distance(knot) > 1:
  51.                     current.carry(knot)
  52.                 current = knot
  53.            
  54.             tail = self.knots[-1]
  55.             self.visited.add((tail.x, tail.y))
  56.  
  57.  
  58. if __name__ == '__main__':
  59.     data = Path("input.txt").read_text().splitlines()
  60.    
  61.     rope = Rope(knots=10)
  62.     for line in data:
  63.         direction, amount = parse(line)
  64.         rope.move(direction, amount)
  65.            
  66.     print(f"visited: {len(rope.visited)}")
  67.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement