-
Notifications
You must be signed in to change notification settings - Fork 0
/
day-9.py
99 lines (83 loc) · 2.72 KB
/
day-9.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#!/usr/bin/env python
def updateTail(tail, head):
# if tail and head are adjacent
if tail[0] >= head[0] - 1 and tail[0] <= head[0] + 1 and tail[1] >= head[1] - 1 and tail[1] <= head[1] + 1:
return tail
elif tail[0] == head[0]:
if tail[1] < head[1]:
return (tail[0], tail[1] + 1)
else:
return (tail[0], tail[1] - 1)
elif tail[1] == head[1]:
if tail[0] < head[0]:
return (tail[0] + 1, tail[1])
else:
return (tail[0] - 1, tail[1])
else:
if head[0] > tail[0]:
if head[1] > tail[1]:
return (tail[0] + 1, tail[1] + 1)
else:
return (tail[0] + 1, tail[1] - 1)
else:
if head[1] > tail[1]:
return (tail[0] - 1, tail[1] + 1)
else:
return (tail[0] - 1, tail[1] - 1)
return tail
def partOne(input):
visited = set((0, 0))
head = (0,0)
tail = (0,0)
for line in input:
[direction, steps] = line.split()
print(line)
for i in range(int(steps)):
if direction == "R":
head = (head[0], head[1] + 1)
elif direction == "L":
head = (head[0], head[1] - 1)
elif direction == "U":
head = (head[0] + 1, head[1])
elif direction == "D":
head = (head[0] - 1, head[1])
else:
print("Invalid direction")
tail = updateTail(tail, head)
visited.add(tail)
return len(visited)
def partTwo(input):
visited = set((0, 0))
head = (0,0)
body = [(0,0) for x in range(0, 9)]
print(body)
for line in input:
[direction, steps] = line.split()
print(line)
for i in range(int(steps)):
if direction == "R":
head = (head[0], head[1] + 1)
elif direction == "L":
head = (head[0], head[1] - 1)
elif direction == "U":
head = (head[0] + 1, head[1])
elif direction == "D":
head = (head[0] - 1, head[1])
else:
print("Invalid direction")
j = 0
while j < len(body):
if j == 0:
body[j] = updateTail(body[j], head)
else:
body[j] = updateTail(body[j], body[j - 1])
j += 1
visited.add(body[8])
return len(visited)
def main():
f = open('./input/day-9.txt', 'r')
input = f.read().splitlines()
print(partOne(input))
print(partTwo(input))
if __name__ == '__main__':
main()