-
Notifications
You must be signed in to change notification settings - Fork 1
/
algorithms.py
345 lines (275 loc) · 10.2 KB
/
algorithms.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
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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
import time
from math import sqrt
import heapq
def getPath(parent_map: dict) -> list[int]:
"""
:param parent_map: Contains each child state as a key and the value is its parent
:return: The path from start state to goal state
"""
path = []
child = 12345678
while True:
path.append(child)
parent = parent_map[child]
# if we find start state we reverse the array, so it is ordered from state to goal
if parent == child:
# parent = child only when start state is reached
path.reverse()
return path
child = parent
def isGoal(state: int) -> bool:
if state == 12345678:
return True
else:
return False
def getChildren(state: int) -> list[int]:
"""
:param state: State in integer form
:return: List of all possible children
"""
state = str(state)
if len(state) == 8:
state = '0' + state
state = list(state)
children = []
index = state.index('0')
row = index // 3
col = index % 3
if row > 0:
# if row > 0, 0 can be swapped with the upper row
child = state.copy()
child[row * 3 + col], child[(row - 1) * 3 + col] = child[(row - 1) * 3 + col], child[row * 3 + col]
children.append(int(''.join(child)))
if row < 2:
# if row < 2, 0 can be swapped with the lower row
child = state.copy()
child[row * 3 + col], child[(row + 1) * 3 + col] = child[(row + 1) * 3 + col], child[row * 3 + col]
children.append(int(''.join(child)))
if col > 0:
# if col > 0, 0 can be swapped with the previous column
child = state.copy()
child[row * 3 + col], child[row * 3 + col - 1] = child[row * 3 + col - 1], child[row * 3 + col]
children.append(int(''.join(child)))
if col < 2:
# if col < 2, 0 can be swapped with the following column
child = state.copy()
child[row * 3 + col], child[row * 3 + col + 1] = child[row * 3 + col + 1], child[row * 3 + col]
children.append(int(''.join(child)))
return children
def BFS(start_state: int) -> tuple:
"""
:param start_state: The start state of the puzzle
:return: path, cost, explored, max_depth, runtime if there is a path, else returns explored, max_depth, runtime
"""
max_depth = 0
found = False
# frontier queue with start state inserted
# frontier queue is a list of lists
# each list consists of the state and its depth in the search tree
frontier = [[start_state, 0]]
frontier_set = set()
frontier_set.add(start_state)
explored = set()
parent_map = {start_state: start_state}
start_time = time.time()
while frontier:
state = frontier.pop(0)
frontier_set.remove(state[0])
explored.add(state[0])
max_depth = max(max_depth, state[1])
if isGoal(state[0]):
found = True
break
for child in getChildren(state[0]):
if child not in frontier_set and child not in explored:
frontier.append([child, state[1] + 1])
frontier_set.add(child)
parent_map[child] = state[0]
runtime = round(time.time() - start_time, 3)
explored = len(explored)
if found:
path = getPath(parent_map)
cost = len(path) - 1
return path, cost, explored, max_depth, runtime
return explored, max_depth, runtime
def getX(state: str, variable: str) -> int:
"""
:param state: The state in str form
:param variable: The char aiming to get its X
:return: X of variable in the state
"""
index = state.index(variable)
if index == 0 or index == 3 or index == 6:
return 1
if index == 1 or index == 4 or index == 7:
return 2
if index == 2 or index == 5 or index == 8:
return 3
def getY(state: str, variable: str) -> int:
"""
:param state: The state in str form
:param variable: The char aiming to get its Y
:return: Y of variable in the state
"""
index = state.index(variable)
if index == 0 or index == 1 or index == 2:
return 3
if index == 3 or index == 4 or index == 5:
return 2
if index == 6 or index == 7 or index == 8:
return 1
def heuristicManhattan(state: int) -> int:
"""
:param state: The state in int form
:return: Manhattan Heuristic for the given state
"""
state = str(state)
if len(state) == 8:
state = '0' + state
x1 = getX(state, '1')
y1 = getY(state, '1')
res = abs(x1 - 2) + abs(y1 - 3)
x2 = getX(state, '2')
y2 = getY(state, '2')
res += abs(x2 - 3) + abs(y2 - 3)
x3 = getX(state, '3')
y3 = getY(state, '3')
res += abs(x3 - 1) + abs(y3 - 2)
x4 = getX(state, '4')
y4 = getY(state, '4')
res += abs(x4 - 2) + abs(y4 - 2)
x5 = getX(state, '5')
y5 = getY(state, '5')
res += abs(x5 - 3) + abs(y5 - 2)
x6 = getX(state, '6')
y6 = getY(state, '6')
res += abs(x6 - 1) + abs(y6 - 1)
x7 = getX(state, '7')
y7 = getY(state, '7')
res += abs(x7 - 2) + abs(y7 - 1)
x8 = getX(state, '8')
y8 = getY(state, '8')
res += abs(x8 - 3) + abs(y8 - 1)
return res
def heuristicEuclidean(state: int) -> int:
"""
:param state: The state in int form
:return: Integer Euclidean Heuristic for the given state
"""
state = str(state)
if len(state) == 8:
state = '0' + state
x1 = getX(state, '1')
y1 = getY(state, '1')
res = sqrt(pow((x1 - 2), 2) + pow((y1 - 3), 2))
x2 = getX(state, '2')
y2 = getY(state, '2')
res += sqrt(pow((x2 - 3), 2) + pow((y2 - 3), 2))
x3 = getX(state, '3')
y3 = getY(state, '3')
res += sqrt(pow((x3 - 1), 2) + pow((y3 - 2), 2))
x4 = getX(state, '4')
y4 = getY(state, '4')
res += sqrt(pow((x4 - 2), 2) + pow((y4 - 2), 2))
x5 = getX(state, '5')
y5 = getY(state, '5')
res += sqrt(pow((x5 - 3), 2) + pow((y5 - 2), 2))
x6 = getX(state, '6')
y6 = getY(state, '6')
res += sqrt(pow((x6 - 1), 2) + pow((y6 - 1), 2))
x7 = getX(state, '7')
y7 = getY(state, '7')
res += sqrt(pow((x7 - 2), 2) + pow((y7 - 1), 2))
x8 = getX(state, '8')
y8 = getY(state, '8')
res += sqrt(pow((x8 - 3), 2) + pow((y8 - 1), 2))
return int(res)
def A(start_state: int, flag: int) -> tuple:
"""
:param start_state: Start state of the puzzle
:param flag: 1 for Euclidean Heuristic | 0 for Manhattan Heuristic
:return: path, cost, explored, max_depth, runtime if there is a path, else returns explored, max_depth, runtime
"""
max_depth = 0
found = False
f = heuristicEuclidean(start_state) if flag == 1 else heuristicManhattan(start_state)
h = f
# frontier heap with start state inserted
# frontier heap is a list of lists
# each list consists of the state, its heuristic and (cost + heuristic)
frontier = [[f, h, start_state]]
frontier_map = {start_state: f}
explored = set()
parent_map = {start_state: start_state}
start_time = time.time()
while frontier:
state = heapq.heappop(frontier)
if state[2] in frontier_map:
frontier_map.pop(state[2])
explored.add(state[2])
g = state[0] - state[1]
max_depth = max(max_depth, g)
if isGoal(state[2]):
found = True
break
for child in getChildren(state[2]):
if child not in frontier_map and child not in explored:
h = heuristicEuclidean(child) if flag == 1 else heuristicManhattan(child)
heapq.heappush(frontier, [h + g + 1, h, child])
max_depth = max(max_depth, g + 1)
frontier_map[child] = h + g
parent_map[child] = state[2]
elif child in frontier_map:
h = heuristicEuclidean(child) if flag == 1 else heuristicManhattan(child)
temp = frontier_map[child]
if h + g < temp:
# if a smaller f was found, insert the state again in the frontier with the new f
# update the parent map with the new parent for the state
heapq.heappush(frontier, [h + g + 1, h, child])
max_depth = max(max_depth, g + 1)
frontier_map[child] = h + g
parent_map[child] = state[2]
runtime = round(time.time() - start_time, 3)
explored = len(explored)
if found:
path = getPath(parent_map)
cost = len(path) - 1
return path, cost, explored, max_depth, runtime
return explored, max_depth, runtime
def DFS(start_state: int) -> tuple:
"""
:param start_state: Start state of the puzzle
:return: path, cost, explored, max_depth, runtime if there is a path, else returns explored, max_depth, runtime
"""
max_depth = 0
found = False
# frontier stack with start state inserted
# frontier stack is a list of lists
# each list consists of the state and its depth
frontier = [[start_state, 0]]
frontier_set = set()
frontier_set.add(start_state)
explored = set()
parent_map = {start_state: start_state}
start_time = time.time()
while frontier:
state = frontier.pop()
frontier_set.remove(state[0])
explored.add(state[0])
max_depth = max(max_depth, state[1])
if isGoal(state[0]):
found = True
break
for child in getChildren(state[0]):
if child not in frontier_set and child not in explored:
frontier.append([child, state[1] + 1])
max_depth = max(max_depth, state[1] + 1)
frontier_set.add(child)
parent_map[child] = state[0]
runtime = round(time.time() - start_time, 3)
explored = len(explored)
if found:
path = getPath(parent_map)
cost = len(path) - 1
return path, cost, explored, max_depth, runtime
return explored, max_depth, runtime