-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAssignment1Q4 Remastered.py
More file actions
276 lines (235 loc) · 7.68 KB
/
Copy pathAssignment1Q4 Remastered.py
File metadata and controls
276 lines (235 loc) · 7.68 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
# from task3 import path_to_next
import numpy as np
import time
'''
DIR_UP = "u"
DIR_DOWN = "d"
DIR_LEFT = "l"
DIR_RIGHT = "r"
MOVE_KEYS={
DIR_UP: (-1, 0),
DIR_DOWN: (1, 0),
DIR_LEFT: (0, -1),
DIR_RIGHT: (0, 1)
}
MOVE_OPS={
DIR_UP: DIR_DOWN,
DIR_DOWN: DIR_UP,
DIR_LEFT: DIR_RIGHT,
DIR_RIGHT: DIR_LEFT
}
'''
class Robot():
def __init__(self, grid: list) -> None:
self._dir_up = "u"
self._dir_down = "d"
self._dir_left = "l"
self._dir_right = "r"
self._dir_vectors = {
self._dir_up: np.array((-1, 0), dtype=np.int_),
self._dir_down: np.array((1, 0), dtype=np.int_),
self._dir_left: np.array((0, -1), dtype=np.int_),
self._dir_right: np.array((0, 1), dtype=np.int_)
}
self._dir_oppsite = {
self._dir_up: self._dir_down,
self._dir_down: self._dir_up,
self._dir_left: self._dir_right,
self._dir_right: self._dir_left
}
self._dir_priority = {
self._dir_up: 1,
self._dir_right: 2,
self._dir_down: 3,
self._dir_left: 4
}
self._map = np.array(grid)
self._map_raw = grid
self._queue_action = []
self._queue_backtrack = []
self._log = []
if self._validate_input():
self._validated = True
self._pos: tuple[int,int] = self._search('X')[0]
else:
self._validated = False
def _validate_input(self) -> bool:
# Validate weather is empty
# raise NotImplemented('Unfinished code.')
if not self._map_raw:
return False
if len(self._map.shape) != 2:
return False
for index,value in np.ndenumerate(self._map):
if not isinstance(value,str):
return False
if value.islower():
self._map[index[0]][index[1]] = value.upper()
if not value in ['X','E','D','W']:
return False
# Validate weather has a robot.
if not (len(self._search('X')) == 1):
return False
return True
# Use given pos and offset to check weather is a empty there.
def _validate_item(self, vector: tuple, item: list) -> bool:
target_row = self._pos[0] + vector[0]
target_column = self._pos[1] + vector[1]
# Prevent Negative list index, cuz it caouse problems.
if (target_row < 0) or (target_column < 0):
return False
try:
if self._map[target_row, target_column] in item:
return True
except IndexError:
return False
else:
return False
# Ilterate threw array to found first given item.
def _search(self, item: str) -> list[tuple[int,int]]:
return_list = []
for index,value in np.ndenumerate(self._map):
if value == item:
return_list.append(index)
else:
return return_list
# Sensor function scans the given direction
def _sensor(self, direction: str) -> list[str]:
scaler = 0
record = []
while True:
scaler = scaler + 1
vector = scaler * self._dir_vectors[direction]
record.append(direction)
if not self._validate_item(vector, ['E', 'D']):
return []
if self._validate_item(vector, ['D']):
return record
# Move to the direction
def _swap(self, direction: str) -> None:
vector = self._dir_vectors[direction] # Convert direction into vector
target_row = self._pos[0] + vector[0]
target_column = self._pos[1] + vector[1]
if not self._validate_item(vector, ['E','D']):
return None
self._map[target_row, target_column] = 'X'
self._map[self._pos[0], self._pos[1]] = 'E'
self._pos = (target_row, target_column)
self._log.append(direction)
return None
# Path to nearest dirt.
def _pnext(self) -> list:
sensors = []
# Scan around using sensors.
# And them sort with requirments.
for key,value in self._dir_vectors.items():
sensor_resoult = self._sensor(key)
sensors.append((len(sensor_resoult),self._dir_priority[key],sensor_resoult))
sensors.sort(key=lambda tuple: (tuple[0], tuple[1]))
# Return The first non-empty list.
# Note that S is already sorted.
for sensor in sensors:
if sensor[2]:
return sensor[2]
return []
'''
def clean_map(self) -> list:
global MOVE_OPS
while True:
pnext = self.path_to_next()
if self.queue_action:
self.queue_action[0][0](self.queue_action[0][1])
self.queue_action.pop(0)
elif (not self.queue_action) and (not pnext):
#Do back track
self.queue_backtrack[-1][0](self.queue_backtrack[-1][1])
self.queue_backtrack.pop(-1)
elif (not self.queue_action) and (pnext):
for moves in pnext:
self.queue_action.append((self.move,moves))
self.queue_backtrack.append((self.move,MOVE_OPS[moves]))
pnext = self.path_to_next()
if (not self.queue_action) and (not self.queue_backtrack) and (not pnext):
break
return self.log
'''
def _scan(self):
moves = self._pnext()
if not moves:
return False
for move in moves:
self._queue_action.append(move)
self._queue_backtrack.append(self._dir_oppsite[move])
return True
def _backtrack(self):
if not self._scan():
self._swap(self._queue_backtrack.pop(-1))
if not self._queue_backtrack:
self._scan()
def _move(self):
self._swap(self._queue_action.pop(0))
def clean(self):
self._scan()
while True:
if self._queue_action:
self._move()
elif self._queue_backtrack:
self._backtrack()
else:
break
return self._log
# list grid: 2D array
# return True: Invalid input, False: Valid Inpuy
def clean_path(world):
r = Robot(world)
return r.clean()
test_case_1 = [
['E', 'D', 'E'],
['D', 'X', 'D'],
['E', 'D', 'E']
]
test_case_2 = [
['E', 'D', 'E', 'E', 'E'],
['W', 'W', 'X', 'D', 'E'],
['E', 'E', 'W', 'E', 'E'],
['E', 'D', 'E', 'E', 'E']
]
test_case_3 = [
['E', 'W', 'D', 'E', 'E'],
['E', 'E', 'X', 'W', 'E'],
['E', 'E', 'W', 'D', 'E'],
['D', 'W', 'E', 'E', 'E']
]
test_case_4 = [
['E', 'E', 'E', 'E', 'E'],
['E', 'D', 'E', 'D', 'E'],
['D', 'E', 'X', 'E', 'D'],
['E', 'E', 'D', 'E', 'E'],
['E', 'E', 'E', 'E', 'E']
]
test_case_5 = [
['E', 'E', 'E', 'D', 'E', 'E', 'E'],
['E', 'D', 'W', 'E', 'E', 'D', 'E'],
['E', 'E', 'W', 'X', 'W', 'E', 'E'],
['E', 'D', 'W', 'D', 'W', 'D', 'E'],
['E', 'E', 'E', 'E', 'E', 'E', 'E']
]
print(clean_path(test_case_1 ))
print(clean_path(test_case_2 ))
print(clean_path(test_case_3 ))
print(clean_path(test_case_4 ))
print(clean_path(test_case_5 ))
'''
print(clean_path([['E', 'D'],
['E', 'E'],
['E', 'X']]))
print(clean_path([['D', 'D'],
['E', 'E'],
['E', 'X']]))
print(clean_path([['E', 'D', 'E'],
['X', 'D', 'E'],
['E', 'D', 'E']]))
print(clean_path([['E', 'D', 'D'],
['D', 'E', 'E'],
['D', 'E', 'X']]))
'''