-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaoc.py
More file actions
324 lines (260 loc) · 8.19 KB
/
Copy pathaoc.py
File metadata and controls
324 lines (260 loc) · 8.19 KB
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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
from collections import defaultdict, deque
from enum import Enum
import heapq
from itertools import starmap
from math import sqrt
import numbers
import operator
from typing import Callable, Iterable, Iterator, Optional, TypeVar
import os
T = TypeVar("T")
p_cache: dict[int, list[int]] = dict()
Point = tuple[int, int]
PathWeightFunc = Callable[["TextGrid", Point, Point], Optional[int]]
NeighbourFunc = Callable[["TextGrid", Point], list[Point]]
class Vector(tuple):
@property
def x(self):
return self[0]
@property
def y(self):
return self[1]
@property
def z(self):
return self[2]
@property
def w(self):
return self[3]
def _apply_operation(self, other: Iterable, op: Callable) -> "Vector":
if isinstance(other, numbers.Number):
other = [other] * len(self)
elif isinstance(other, Direction):
other = other.value
if isinstance(other, Iterable):
return Vector(starmap(op, zip(self, other)))
raise Exception("Operand must be iterable")
def magnitude(self):
return sqrt(sum(n**2 for n in self))
def __add__(self, other):
return self._apply_operation(other, operator.add)
def __sub__(self, other):
return self._apply_operation(other, operator.sub)
def __truediv__(self, other):
return self._apply_operation(other, operator.truediv)
def __mul__(self, other):
return self._apply_operation(other, operator.mul)
class Direction(Enum):
NORTH = (0, -1)
NORTH_EAST = (1, -1)
EAST = (1, 0)
SOUTH_EAST = (1, 1)
SOUTH = (0, 1)
SOUTH_WEST = (-1, 1)
WEST = (-1, 0)
NORTH_WEST = (-1, -1)
@classmethod
def all(cls) -> deque["Direction"]:
return deque(
[
cls.NORTH,
cls.NORTH_EAST,
cls.EAST,
cls.SOUTH_EAST,
cls.SOUTH,
cls.SOUTH_WEST,
cls.WEST,
cls.NORTH_WEST,
]
)
@classmethod
def cardinal(cls) -> deque["Direction"]:
return deque(
[
cls.NORTH,
cls.EAST,
cls.SOUTH,
cls.WEST,
]
)
@classmethod
def intercardinal(cls) -> deque["Direction"]:
return deque(
[
cls.NORTH_EAST,
cls.SOUTH_EAST,
cls.SOUTH_WEST,
cls.NORTH_WEST,
]
)
@classmethod
def cw(cls, start: "Direction") -> deque["Direction"]:
all = cls.all()
all.rotate(-all.index(start))
return all
@classmethod
def ccw(cls, start: "Direction") -> deque["Direction"]:
all = cls.all()
all.rotate(-all.index(start) - 1)
all.reverse()
return all
def apply(self, point: Point) -> Point:
return (point[0] + self.value[0], point[1] + self.value[1])
class TextGrid:
lines: list[str]
width: int
height: int
def __init__(self, lines: list[str], strip: bool = True):
self.lines = [l.strip() for l in lines] if strip else lines
if not all(len(l) == len(self.lines[0]) for l in self.lines):
raise Exception("Bad shape")
self.width = len(self.lines[0])
self.height = len(self.lines)
def find_all(self, char: str) -> list[Point]:
results = []
for x in range(self.width):
for y in range(self.height):
if self[x, y] == char:
results.append((x, y))
return results
def get_neighbours(
self,
p: Point,
directions: Iterable[Direction] = Direction.all(),
include_none: bool = False,
):
return [
d.apply(p) for d in directions if include_none or self[d.apply(p)] != None
]
def _search(
self,
start: Point,
get_weight: PathWeightFunc,
popper: Callable[[deque[Point]], Point],
get_neighbours: NeighbourFunc = get_neighbours,
acyclic: bool = False,
) -> Iterator[tuple[str, Point]]:
visited = set()
s = deque([start])
while s:
cur = popper(s)
if cur in visited and not acyclic:
continue
visited.add(cur)
yield self[cur], (cur[0], cur[1])
neighbours = get_neighbours(self, cur)
for n in neighbours:
if (
self[n] != None
and (n not in visited or acyclic)
and get_weight(self, cur, n) is not None
):
s.append(n)
def dfs(
self,
start: Point,
get_weight: PathWeightFunc,
acyclic: bool = False,
get_neighbours: NeighbourFunc = get_neighbours,
) -> Iterator[tuple[str, Point]]:
return self._search(start, get_weight, deque.pop, get_neighbours, acyclic)
def bfs(
self,
start: Point,
get_weight: PathWeightFunc,
acyclic: bool = False,
get_neighbours: NeighbourFunc = get_neighbours,
) -> Iterator[tuple[str, Point]]:
return self._search(start, get_weight, deque.popleft, get_neighbours, acyclic)
def shortest_path(
self,
p1: Point,
p2: Point,
get_weight: PathWeightFunc,
get_neighbours: NeighbourFunc = get_neighbours,
heuristic: PathWeightFunc = None,
) -> Optional[tuple[int, deque[Point]]]:
distance = defaultdict(lambda: float("inf"))
distance[p1] = 0
parents = dict()
q = [(0, p1)]
while q:
cur_weight, cur = heapq.heappop(q)
if cur == p2:
break
if cur_weight > distance[cur]:
continue
neighbours = get_neighbours(self, cur)
for n in neighbours:
weight = get_weight(self, cur, n)
if weight is None:
continue
weight += distance[cur]
if heuristic:
weight += heuristic(self, cur, p2)
if weight < distance[n]:
distance[n] = weight
parents[n] = cur
heapq.heappush(q, (weight, n))
if p2 not in parents:
return None
path = deque()
path.appendleft(p2)
back = p2
while (back := parents[back]) != p1:
path.appendleft(back)
return distance[p2], path
def find(self, char: str) -> Optional[Point]:
for x in range(self.width):
for y in range(self.height):
if self[x, y] == char:
return (x, y)
@classmethod
def from_file(cls, path: str, strip: bool = True) -> "TextGrid":
with open(path) as f:
lines = f.readlines()
return cls(lines, strip)
def __getitem__(self, index: Point) -> Optional[str]:
try:
if index[0] >= 0 and index[1] >= 0:
return self.lines[index[1]][index[0]]
except:
pass
def __setitem__(self, index: Point, val: str) -> Optional[str]:
ret = None
try:
if (
index[0] >= 0
and index[1] >= 0
and index[0] < self.width
and index[1] < self.height
):
l = self.lines[index[1]]
self.lines[index[1]] = l[: index[0]] + val + l[index[0] + 1 :]
except:
pass
def __str__(self):
s = ""
for l in self.lines:
s += l + os.linesep
return s
def try_or_default(fn: Callable[[], T], default: T) -> T:
try:
return fn()
except:
return default
def permute(choose: int, base: int) -> list[list[int]]:
if choose in p_cache:
return p_cache[choose]
result = []
for counter in range(pow(base, choose)):
p = [0] * choose
i = 0
current = counter
p[i] = current % base
while current >= base:
current = int(current / base)
i += 1
p[i] = current % base
result.append(p)
p_cache[choose] = result
return result