Advertisement
Guest User

Untitled

a guest
Jun 19th, 2019
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.94 KB | None | 0 0
  1. from Board import Board
  2. import heapq as hq
  3. class Solver():
  4.     def __init__(self, board, priority):
  5.         self.board = board
  6.         self.priority = priority
  7.         self.move = 0
  8.         self.opened = []
  9.         self.closed = []
  10.     def moves(self):
  11.         return self.move
  12.     def priority_search(self, board):
  13.         if self.priority == 'hamming':
  14.             return board.hamming()
  15.         else:
  16.             return board.manhattan()
  17.  
  18.     def solve(self):
  19.         hq.heappush(self.opened, (self.priority_search(self.board), self.move, [], self.board))
  20.  
  21.         while len(self.opened) != 0:
  22.             current = hq.heappop(self.opened)
  23.             self.closed.append(current[-1])
  24.             path = current[2]
  25.  
  26.             if current[-1].isGoal():
  27.                 current[2].append(current[-1])
  28.                 return current[2]
  29.  
  30.             elif not (current[-1].twin()):
  31.                 self.closed = []
  32.                 return False
  33.  
  34.             for neighbor in current[-1]:
  35.                 path1 = path.copy()
  36.                 path1.append(current[-1])
  37.                 if neighbor in self.closed:
  38.                     continue
  39.                 data = (self.priority_search(neighbor) + current[1] + 1, current[1] + 1,
  40.                         path1, neighbor)
  41.                 self.move = data[1]
  42.                 hq.heappush(self.opened, data)
  43.  
  44.         return self.closed
  45.     def __iter__(self):
  46.         if len(self.closed) == 0:
  47.             return "The board is unsolvable"
  48.         return SolverIterator(self.closed)
  49. class SolverIterator:
  50.     def __init__(self, output):
  51.         self.output = output
  52.         self.step = -1
  53.         self.length = len(self.output)
  54.     def __next__(self):
  55.         self.step += 1
  56.         if self.step == self.length:
  57.             raise StopIteration
  58.         return self.output[self.step]
  59.  
  60. b = Board([1, 2, 3,4, 5, 6, " ", 7, 8])
  61. s = Solver(b, "hamming")
  62. s.solve()
  63. for i in s:
  64.     print(i)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement