Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from Board import Board
- import heapq as hq
- class Solver():
- def __init__(self, board, priority):
- self.board = board
- self.priority = priority
- self.move = 0
- self.opened = []
- self.closed = []
- def moves(self):
- return self.move
- def priority_search(self, board):
- if self.priority == 'hamming':
- return board.hamming()
- else:
- return board.manhattan()
- def solve(self):
- hq.heappush(self.opened, (self.priority_search(self.board), self.move, [], self.board))
- while len(self.opened) != 0:
- current = hq.heappop(self.opened)
- self.closed.append(current[-1])
- path = current[2]
- if current[-1].isGoal():
- current[2].append(current[-1])
- return current[2]
- elif not (current[-1].twin()):
- self.closed = []
- return False
- for neighbor in current[-1]:
- path1 = path.copy()
- path1.append(current[-1])
- if neighbor in self.closed:
- continue
- data = (self.priority_search(neighbor) + current[1] + 1, current[1] + 1,
- path1, neighbor)
- self.move = data[1]
- hq.heappush(self.opened, data)
- return self.closed
- def __iter__(self):
- if len(self.closed) == 0:
- return "The board is unsolvable"
- return SolverIterator(self.closed)
- class SolverIterator:
- def __init__(self, output):
- self.output = output
- self.step = -1
- self.length = len(self.output)
- def __next__(self):
- self.step += 1
- if self.step == self.length:
- raise StopIteration
- return self.output[self.step]
- b = Board([1, 2, 3,4, 5, 6, " ", 7, 8])
- s = Solver(b, "hamming")
- s.solve()
- for i in s:
- print(i)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement