-
Notifications
You must be signed in to change notification settings - Fork 0
/
driver_3.py
284 lines (250 loc) · 9.62 KB
/
driver_3.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
import queue
import random
import math
import sys
sys.setrecursionlimit(5000)
class Solver(object):
def __init__(self, puzzleConfig, method):
self.configArr = puzzleConfig.split(",")
self.configArr = list(map(int, self.configArr))
if not self.isSquare(len(self.configArr)):
raise Exception ("The configuration is not a square")
#elif not self.isSolvable():
# raise Exception ("The configuration is not solvable")
else:
self.n = int(math.sqrt(len(self.configArr)))
self.method = method
self.path = []
self.puzzle = [[0 for x in range(self.n)] for y in range(self.n)]
k = 0
for x in range(self.n):
for y in range(self.n):
self.puzzle[x][y] = self.configArr[k]
k += 1
self.rootState = PuzzleState(self.puzzle)
self.rootState.showPuzzle()
if method == "bfs":
self.bfs_search(False)
elif method == "dfs":
self.dfs_search()
elif method == "ast":
self.ast_search(False)
def isSquare(self, num):
root = math.sqrt(num)
if (int(root + 0.5) ** 2 == num):
return True
else:
return False
def isSolvable(self):
inversions = 0
arr = self.configArr.copy()
arr.remove(0)
for x in range(len(arr)):
for y in range(x + 1, len(arr)):
if arr[y] > arr[x]:
inversions += 1
if inversions % 2 == 0:
return True
else:
return False
def bfs_search(self, ceroUp = True):
initialState = self.rootState
q = queue.Queue()
#Save puzzle configurations
visited = []
frontier = []
q.put(initialState)
while not q.empty():
currentState = q.get()
if currentState.isSolved(ceroUp):
print("Solved")
currentState.showPuzzle()
self.getPath(currentState)
return currentState
else:
visited.append(currentState.puzzle)
if currentState.puzzle in frontier: frontier.remove(currentState.puzzle)
children = currentState.expandNode()
for c in children:
if c.puzzle not in visited and c.puzzle not in frontier:
q.put(c)
frontier.append(c.puzzle)
return None
def dfs_search(self, ceroUp = True):
initialState = self.rootState
q = queue.LifoQueue()
visited = []
q.put(initialState)
while not q.empty():
currentState = q.get()
if currentState.isSolved(ceroUp):
print("Solved")
currentState.showPuzzle()
self.getPath(currentState)
return currentState
else:
visited.append(currentState.puzzle)
children = currentState.expandNode()
for c in children:
if c.puzzle not in visited:
q.put(c)
def ast_search(self, ceroUp = True):
initialState = self.rootState
q = queue.PriorityQueue()
counter = 0
visited = []
frontier = []
q.put((1, 0, initialState))
while not q.empty():
currentState = q.get()[2]
#currentState.showPuzzle()
if currentState.isSolved(ceroUp):
print("Solved")
currentState.showPuzzle()
self.getPath(currentState)
return currentState
else:
visited.append(currentState.puzzle)
if currentState.puzzle in frontier: frontier.remove(currentState.puzzle)
children = currentState.expandNode()
for c in children:
counter += 1
if c.puzzle not in visited and c.puzzle not in frontier:
q.put((c.manhattanDistance(ceroUp) + c.cost, counter,c))
frontier.append(c.puzzle)
def getPath(self, PuzzleState):
self.path.append(PuzzleState.action)
if PuzzleState.parent is not None:
self.getPath(PuzzleState.parent)
else:
self.path.reverse()
print(self.path)
class PuzzleState(object):
def __init__(self, puzzle, parent=None, action="Initial", cost = 0, depth = 0):
self.puzzle = puzzle
self.parent = parent
self.action = action
self.cost = cost
self.depth = depth
self.children = [] #Array of other Puzzle States
for x in range(len(self.puzzle)):
for y in range(len(self.puzzle)):
if self.puzzle[x][y] == 0:
self.blankRow = x
self.blankColumn = y
break
self.n = len(self.puzzle)
def missplacedPieces(self, ceroUp):
puzzleArr = []
for x in range(len(self.puzzle)):
for y in range(len(self.puzzle)):
puzzleArr.append(self.puzzle[x][y])
solvedPuzzle = puzzleArr.copy()
solvedPuzzle.sort()
if ceroUp is False:
solvedPuzzle.remove(0)
solvedPuzzle.append(0)
missplacedPieces = 0
for x in range(len(puzzleArr)):
if not puzzleArr[x] == solvedPuzzle[x]:
missplacedPieces += 1
return missplacedPieces
def get2DIndex(self, array, value):
i = 0
for li in array:
if value in li:
return (i, li.index(value))
i += 1
return None
def manhattanDistance(self, ceroUp = True):
solvedPuzzle = [[0 for x in range(len(self.puzzle))] for y in range(len(self.puzzle))]
mDistance = 0
k = 0
if ceroUp:
k = 0
else:
k = 1
for x in range(len(self.puzzle)):
for y in range(len(self.puzzle)):
solvedPuzzle[x][y] = k
k += 1
if ceroUp is False:
solvedPuzzle[len(solvedPuzzle) - 1][len(solvedPuzzle) - 1] = 0
for x in range(len(self.puzzle)):
for y in range(len(self.puzzle)):
coord = self.get2DIndex(solvedPuzzle, self.puzzle[x][y])
mDistance += abs(x - coord[0]) + abs(y - coord[1])
return mDistance
def isSolved(self, ceroUp = True):
puzzleArr = []
for x in range(len(self.puzzle)):
for y in range(len(self.puzzle)):
puzzleArr.append(self.puzzle[x][y])
solvedPuzzle = puzzleArr.copy()
solvedPuzzle.sort()
if ceroUp is False:
solvedPuzzle.remove(0)
solvedPuzzle.append(0)
if solvedPuzzle == puzzleArr:
return True
else:
return False
def showPuzzle(self):
for x in range(len(self.puzzle)):
for y in range(len(self.puzzle)):
print("{:<4}".format(self.puzzle[x][y]), end="")
print()
print("--------------")
def moveLeft(self):
if self.blankColumn == 0:
return None
else:
newPuzzleState = [row[:] for row in self.puzzle]
value = newPuzzleState[self.blankRow][self.blankColumn - 1]
newPuzzleState[self.blankRow][self.blankColumn - 1] = 0
newPuzzleState[self.blankRow][self.blankColumn] = value
return PuzzleState(newPuzzleState, self, "Left", self.cost + 1, self.depth + 1)
def moveRight(self):
if self.blankColumn == self.n - 1:
return None
else:
newPuzzleState = [row[:] for row in self.puzzle]
value = newPuzzleState[self.blankRow][self.blankColumn + 1]
newPuzzleState[self.blankRow][self.blankColumn + 1] = 0
newPuzzleState[self.blankRow][self.blankColumn] = value
return PuzzleState(newPuzzleState, self, "Right", self.cost + 1, self.depth + 1)
def moveUp(self):
if self.blankRow == 0:
return None
else:
newPuzzleState = [row[:] for row in self.puzzle]
value = newPuzzleState[self.blankRow - 1][self.blankColumn]
newPuzzleState[self.blankRow - 1][self.blankColumn] = 0
newPuzzleState[self.blankRow][self.blankColumn] = value
return PuzzleState(newPuzzleState, self, "Up", self.cost + 1, self.depth + 1)
def moveDown(self):
if self.blankRow == self.n - 1:
return None
else:
newPuzzleState = [row[:] for row in self.puzzle]
value = newPuzzleState[self.blankRow + 1][self.blankColumn]
newPuzzleState[self.blankRow + 1][self.blankColumn] = 0
newPuzzleState[self.blankRow][self.blankColumn] = value
return PuzzleState(newPuzzleState, self, "Down", self.cost + 1, self.depth + 1)
def expandNode(self):
if len(self.children) == 0:
upChild = self.moveUp()
if upChild is not None:
self.children.append(upChild)
downChild = self.moveDown()
if downChild is not None:
self.children.append(downChild)
leftChild = self.moveLeft()
if leftChild is not None:
self.children.append(leftChild)
rightChild = self.moveRight()
if rightChild is not None:
self.children.append(rightChild)
return self.children
S = Solver("6,1,7,8,2,4,3,0,5", "bfs")
"""1,4,3,2,0,5,8,7,6"""