-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path9-1.py
56 lines (49 loc) · 1.48 KB
/
9-1.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import numpy as np
data = []
with open(f"9.txt", "r") as file:
data = file.read().splitlines()
class Rope:
def __init__(self, x, y):
self.headX = x
self.headY = y
self.tailX = x
self.tailY = y
self.tailHistory = []
def moveTailOneStep(self):
if abs(self.tailX - self.headX) > 1:
if self.tailX > self.headX:
self.tailX -= 1
else:
self.tailX += 1
self.tailY = self.headY
if abs(self.tailY - self.headY) > 1:
if self.tailY > self.headY:
self.tailY -= 1
else:
self.tailY += 1
self.tailX = self.headX
self.tailHistory.append((self.tailX, self.tailY))
def moveHeadOneStep(self, direction):
if direction == "U":
self.headY -= 1
elif direction == "D":
self.headY += 1
elif direction == "L":
self.headX -= 1
elif direction == "R":
self.headX += 1
else:
raise ValueError("Invalid direction")
self.moveTailOneStep()
def move(self, direction, steps):
for i in range(steps):
self.moveHeadOneStep(direction)
def __repr__(self):
return self.tailHistory()
rope = Rope(0, 0)
for row in data:
instruction = []
instruction = row.split()
instruction[1] = int(instruction[1])
rope.move(instruction[0], instruction[1])
print(len(set(rope.tailHistory)))