Advertisement
illuminati229

Untitled

Dec 9th, 2022
320
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.05 KB | None | 0 0
  1. def adjacent(knot1, knot2):
  2.     if abs(knot1.x - knot2.x) <= 1 and abs(knot1.y - knot2.y) <= 1:
  3.         return True
  4.     else:
  5.         return False
  6.  
  7.  
  8. class Rope:
  9.     class Knot:
  10.         def __init__(self, pos):
  11.             self.x = pos[0]
  12.             self.y = pos[1]
  13.             self.history = [pos]
  14.  
  15.         def get_pos(self):
  16.             return self.x, self.y
  17.  
  18.     def __init__(self, rope_length=2, start_pos=(0, 0)):
  19.         self.knots = [self.Knot(start_pos) for i in range(rope_length)]
  20.         self.head = self.knots[0]
  21.         self.rope_length = rope_length
  22.  
  23.     def move(self, direction):
  24.         if direction == 'D':
  25.             self.head.y -= 1
  26.         elif direction == 'U':
  27.             self.head.y += 1
  28.         elif direction == 'R':
  29.             self.head.x += 1
  30.         elif direction == 'L':
  31.             self.head.x -= 1
  32.         self.head.history.append(self.head.get_pos())
  33.         for i in range(1,self.rope_length):
  34.             current_knot = self.knots[i]
  35.             prior_knot = self.knots[i-1]
  36.             if adjacent(current_knot, prior_knot):
  37.                 current_knot.history.append(current_knot.get_pos())
  38.             else:
  39.                 if current_knot.x != prior_knot.x:
  40.                     delta_x = prior_knot.x - current_knot.x
  41.                     current_knot.x += delta_x//abs(delta_x)
  42.                 if current_knot.y != prior_knot.y:
  43.                     delta_y = prior_knot.y - current_knot.y
  44.                     current_knot.y += delta_y//abs(delta_y)
  45.                 current_knot.history.append(current_knot.get_pos())
  46.  
  47.  
  48. def day09(filepath, length=2):
  49.     with open(filepath) as fin:
  50.         lines = [line.split() for line in fin.readlines()]
  51.  
  52.     rope = Rope(length)
  53.     for line in lines:
  54.         for i in range(int(line[1])):
  55.             rope.move(line[0])
  56.  
  57.     return len(set(rope.knots[-1].history))
  58.  
  59.  
  60. def main():
  61.     assert day09('test09') == 13
  62.     print(day09('input09'))
  63.  
  64.     assert day09('test09_2', 10) == 36
  65.     print(day09('input09', 10))
  66.  
  67.  
  68. if __name__ == '__main__':
  69.     main()
  70.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement