-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolver.py
285 lines (251 loc) · 8.33 KB
/
Solver.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
# Implements BFS, DFS, GBFS and A* to solve n-by-n sliding puzzle
# Used for the graph searches of bfs, dfs, gbfs, and A*
class Node:
# root node receives string 'root'
def __init__(self, parent, state, board):
self.parent = parent
self.state = state
self.num = board.num_created
self.algorithm = board.algorithm
self.node_depth = board.depth
if self.algorithm == 'GBFS' or self.algorithm == 'A*':
self.size = board.size
self.locations = self.get_goal_locations()
self.heuristic = self.get_heuristics()
# Less than operator for sort() or other sorting algorithms
def __lt__(self, other):
return self.num < other.num
# creates a list of states that represents the path found by the algorithm
def get_path(self):
current = self
output = [current.state]
while current.parent != 'root':
current = current.parent
output.insert(0, current.state)
return output
# returns heuristics value associated to the node based on Manhattan Distance
def get_heuristics(self):
curr_state = self.state
zero_index = curr_state.index(' ')
mod_state = curr_state[:zero_index] + '0' + curr_state[zero_index + 1:]
output = 0
for i in range(len(mod_state)):
goal_row = self.locations[i].pop(0)
goal_col = self.locations[i].pop(0)
if i < 10:
piece = str(i)
else:
piece = convert_digit_to_char(i)
index = mod_state.index(piece)
curr_row = int(index / self.size)
curr_col = index % self.size
output += abs(goal_row - curr_row) + abs(goal_col - curr_col)
return output
# sets the locations needed to calculate heuristics
def get_goal_locations(self):
size = len(self.state)
if size == 4:
return {
# Goal state
# 2 1
# 3 0
0: [1, 1],
1: [0, 1],
2: [0, 0],
3: [1, 0]
}
elif size == 9:
return {
0: [0, 0],
1: [0, 1],
2: [0, 2],
3: [1, 0],
4: [1, 1],
5: [1, 2],
6: [2, 0],
7: [2, 1],
8: [2, 2]
}
elif size == 16:
return {
0: [3, 3],
1: [0, 0],
2: [0, 1],
3: [0, 2],
4: [0, 3],
5: [1, 0],
6: [1, 1],
7: [1, 2],
8: [1, 3],
9: [2, 0],
10: [2, 1],
11: [2, 2],
12: [2, 3],
13: [3, 0],
14: [3, 1],
15: [3, 2]
}
else:
print("Locations never got assigned in get_goal_locations()")
# Converts number to the corresponding character
def convert_digit_to_char(digit: int):
output = ''
if digit == 10:
output = 'A'
elif digit == 11:
output = 'B'
elif digit == 12:
output = 'C'
elif digit == 13:
output = 'D'
elif digit == 14:
output = 'E'
elif digit == 15:
output = 'F'
else:
print("Digit did not get converted to char in convert_digit_to_char()")
return output
# Counts number of inversions in a given list representation of an n x n game state
def inversion_count(the_list):
output = 0
blank_position = ' '
for i in range(0, len(the_list)):
for j in range(i + 1, len(the_list)):
if the_list[j] != blank_position and the_list[i] != blank_position and the_list[i] > the_list[j]:
output += 1
return output
# determines if a game state is solvable
def is_solvable(board):
inversions = inversion_count(board.the_list)
output = True
# odd case for board size
if board.size % 2 == 1 and inversions % 2 == 1:
output = False
# even case
elif board.size % 2 == 0:
check = inversions + board.row_of_blank
if check % 2 == 1:
output = True
else:
output = False
return output
# Performs BFS on sliding puzzle for solution; fringe = queue
# returns -1 if failed, returns 0 if successful
def breath_first_search(board):
visited = set()
visited.add(board.list_as_str)
root = Node("root", board.list_as_str, board)
fringe = [root]
depth = 0
while fringe:
size = len(fringe)
if size > board.max_fringe:
board.max_fringe = size
for i in range(size):
current = fringe.pop(0)
board.num_expanded += 1
if current.state == board.goal_state:
board.path = current.get_path()
return 0
add_child(board, visited, current, fringe)
depth += 1
board.depth = depth
return -1
# Performs the given search algorithm (dfs) to an n x n sliding puzzle; fringe = stack
def depth_first_search(board):
visited = set()
visited.add(board.list_as_str)
root = Node("root", board.list_as_str, board)
fringe = [root]
depth = 0
while fringe:
size = len(fringe)
if size > board.max_fringe:
board.max_fringe = size
for i in range(size):
current = fringe.pop()
board.num_expanded += 1
if current.state == board.goal_state:
board.path = current.get_path()
return 0
add_child(board, visited, current, fringe)
depth += 1
board.depth = depth
return -1
# Performs gbfs to an n x n sliding puzzle: fringe priority queue, f(x) = h(x)
def greedy_best_first_search(board):
visited = set()
visited.add(board.list_as_str)
root = Node("root", board.list_as_str, board)
fringe = [(root.heuristic, root)]
depth = 0
while fringe:
size = len(fringe)
if size > board.max_fringe:
board.max_fringe = size
for i in range(size):
curr_tuple = fringe.pop(0)
current = curr_tuple[1]
board.num_expanded += 1
if current.state == board.goal_state:
board.path = current.get_path()
return 0
add_child_heuristics(board, visited, current, fringe)
depth += 1
board.depth = depth
return -1
# Performs A* search to an n x n sliding puzzle; fringe priority queue, f(x) = g(x) + h(x)
def a_star_search(board):
visited = set()
visited.add(board.list_as_str)
root = Node("root", board.list_as_str, board)
fringe = [(root.heuristic, root)]
depth = 0
while fringe:
size = len(fringe)
if size > board.max_fringe:
board.max_fringe = size
for i in range(size):
curr_tuple = fringe.pop(0)
current = curr_tuple[1]
board.num_expanded += 1
if current.state == board.goal_state:
board.path = current.get_path()
return 0
add_child_heuristics(board, visited, current, fringe)
depth += 1
board.depth = depth
return -1
# adds child to tree search
def add_child(board, visited, current, fringe):
index = current.state.index(' ')
mapping = board.mapping
for i in mapping[index]:
s = swap(current.state, index, i)
if s not in visited:
visited.add(s)
fringe.append(Node(current, s, board))
board.num_created += 1
# adds child to tree search with heuristics
def add_child_heuristics(board, visited, current, fringe):
index = current.state.index(' ')
mapping = board.mapping
for i in mapping[index]:
s = swap(current.state, index, i)
if s not in visited:
visited.add(s)
child = Node(current, s, board)
if board.algorithm == "GBFS":
fringe.append((child.heuristic, child))
else:
fringe.append((child.heuristic + child.node_depth, child))
fringe.sort(reverse=False)
# conducts movement and returns updated state
def swap(current: str, index: int, i: int):
s = list(current)
s[index] = s[i]
s[i] = ' '
output = ''
for i in s:
output += i
return output