-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutils.py
124 lines (99 loc) · 2.94 KB
/
utils.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
class Node:
def __init__(self, state, root=None):
self.state = state
self.root = root
class Vector:
def __init__(self, x, y, height, width):
self.x = x
self.y = y
self.width = width
self.height = height
def plus(self, other, x, y):
# Addition to get the next a adjacent
return Vector(other.x + x, other.y + y, self.height, self.width)
def is_inside(self):
# check if we are still inside the grid
return 0 <= self.x < self.height and 0 <= self.y < self.width
def directions(self, key='four'):
directions = {
'UP': (0, 1),
'DOWN': (0, -1),
'RIGHT': (1, 0),
'LEFT': (-1, 0)
}
if key == 'all':
directions['NW'] = (-1, 1)
directions['NE'] = (1, 1)
directions['SW'] = (-1, -1)
directions['SE'] = (1, -1)
return directions
def neighbouring_vectors(coords, h, w, key='four'):
x, y = coords
v = Vector(x, y, h, w)
directions = v.directions(key)
neighbours = []
for direction in directions:
x1, y1 = directions[direction]
new_v = v.plus(v, x1, y1)
if new_v.is_inside():
neighbours.append(new_v)
return neighbours
def process_data(grid):
# part two of AoC day 15, 2021
grid1 = []
grid2 = []
for line in grid:
n = len(line)
to_add = '1' * n
new_line = line
temp = line
for i in range(4):
tl = temp.replace('9', '0')
temp = str(int(tl) + int(to_add))
new_line += temp
grid1.append(new_line)
temp_grid = grid1
for i in range(4):
ng = []
for line in temp_grid:
n = len(line)
t_add = '1' * n
line = line.replace('9', '0')
new_l = str(int(line) + int(t_add))
ng.append(new_l)
grid1 += ng
temp_grid = ng
return grid1
def create_map(grid, s, g, key='four'):
mapp = {}
h = len(grid) # height
w = len(grid[0]) # width
start = None
goal = None
for x, row in enumerate(grid):
for y, point in enumerate(row):
if point == s:
start = (x, y)
if point == g:
goal = (x, y)
vecs = neighbouring_vectors((x, y), h, w, key)
if key == 'all' or key == 'chiton':
mapp[(x, y)] = (int(point), vecs)
else:
mapp[(point, (x, y))] = vecs
return mapp, (start, goal)
def contains(iterable, item):
for it in iterable:
if it.state == item.state:
return True
return False
def find_start_goal(grid, s, g):
start = None
goal = None
for x, row in enumerate(grid):
for y, point in enumerate(row):
if point == s:
start = (x, y)
if point == g:
goal = (x, y)
return start, goal