-
Notifications
You must be signed in to change notification settings - Fork 0
/
day3.py
67 lines (51 loc) · 2.05 KB
/
day3.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
# http://adventofcode.com/2017/day/3
# hint: https://oeis.org/A141481
def check_bounce_needed(horizontal_pos, vertical_pos):
return (horizontal_pos == vertical_pos) \
or (horizontal_pos < 0 and horizontal_pos == -vertical_pos) \
or (horizontal_pos > 0 and horizontal_pos == 1 - vertical_pos)
# part 1 is simple math though, bottom right corners are odd square numbers
# here's a brute force solution, just for the sake of coding
def part1(goal):
horizontal_pos = 0
vertical_pos = 0
horizontal_delta = 0
vertical_delta = -1
step = 0
while True:
step += 1
if goal == step:
return (abs(horizontal_pos) + abs(vertical_pos))
if check_bounce_needed(horizontal_pos, vertical_pos):
horizontal_delta, vertical_delta = -vertical_delta, horizontal_delta
# step
horizontal_pos, vertical_pos = horizontal_pos+horizontal_delta, vertical_pos+vertical_delta
def part2(goal):
horizontal_pos = 0
vertical_pos = 0
horizontal_delta = 0
vertical_delta = -1
spiral = {}
nav_coords = [(1, 0), (1, -1),
(0, -1), (-1, -1),
(-1, 0), (-1, 1),
(0, 1), (1, 1)]
while True:
sum = 0
for offset in nav_coords:
horizontal_offset, vertical_offset = offset
if (horizontal_pos + horizontal_offset, vertical_pos + vertical_offset) in spiral:
sum += spiral[(horizontal_pos + horizontal_offset, vertical_pos + vertical_offset)]
if sum > goal:
return sum
if (horizontal_pos, vertical_pos) == (0, 0): # center of the spiral
spiral[(0, 0)] = 1
else:
spiral[(horizontal_pos, vertical_pos)] = sum
if check_bounce_needed(horizontal_pos, vertical_pos):
horizontal_delta, vertical_delta = -vertical_delta, horizontal_delta
# step
horizontal_pos, vertical_pos = horizontal_pos+horizontal_delta, vertical_pos+vertical_delta
input = 312051
print(part1(input))
print(part2(input))