Sunday, December 18, 2011

Hanoi Towers solver (python)

This is not the most elegant of efficient piece of code, but it was quite fun to write (http://www.ideone.com/g6Zhb):


def print_game(board):
for l in board:
print l
print "----"


def initial_state(board,count):
board[0] = range(count,0,-1)
board[1] = []
board[2] = []

def goal_state(board,count):
board[0] = []
board[1] = []
board[2] = range(count,0,-1)


def children(board):
children = list()
if board[0] != []:
val = board[0][-1]
if len(board[1]) == 0 or board[1][-1] > val:
#print_game(board)
child = list([[],[],[]])
child[0] = board[0][0:-1]
child[1] = board[1][:]
child[1].append(val)
child[2] = board[2][:]
children.append(child)
#print_game(child)
if len(board[2]) == 0 or board[2][-1] > val:
#print_game(board)
child = list([[],[],[]])
child[0] = board[0][0:-1]
child[1] = board[1][:]
child[2] = board[2][:]
child[2].append(val)
children.append(child)
#print_game(child)
if board[1] != []:
val = board[1][-1]
if len(board[0]) == 0 or board[0][-1] > val:
#print_game(board)
child = list([[],[],[]])
child[0] = board[0][:]
child[0].append(val)
child[1] = board[1][0:-1]
child[2] = board[2][:]
children.append(child)
#print_game(child)
if len(board[2]) == 0 or board[2][-1] > val:
#print_game(board)
child = list([[],[],[]])
child[0] = board[0][:]
child[1] = board[1][0:-1]
child[2] = board[2][:]
child[2].append(val)
children.append(child)
#print_game(child)
if board[2] != []:
val = board[2][-1]
if len(board[0]) == 0 or board[0][-1] > val:
#print_game(board)
child = list([[],[],[]])
child[0] = board[0][:]
child[0].append(val)
child[1] = board[1][:]
child[2] = board[2][0:-1]
children.append(child)
#print_game(child)
if len(board[1]) == 0 or board[1][-1] > val:
#print_game(board)
child = list([[],[],[]])
child[0] = board[0][:]
child[1] = board[1][:]
child[1].append(val)
child[2] = board[2][0:-1]
children.append(child)
#print_game(child)
return children

def isInExplored(explored,state):
for s in explored:
if s == state:
return True
return False

def main():
board = list([[],[],[]])
goal = list([[],[],[]])
initial_state(board,7)
goal_state(goal,7)
frontier = []
level = []
currentLevel = 0
explored = []
path = []
parent = [0]
frontier.append(board)
level.append(currentLevel)
while len(frontier) > 0:
state = frontier.pop(0)
currentLevel = level.pop(0)
father = parent.pop(0)
#print currentLevel
#print_game(state)
if state == goal:
print "GOAL FOUND:"
print currentLevel
print_game(state)
for i in range(currentLevel):
print_game(explored[father])
father = path[father]

explored.append(state)
path.append(father)
for child in children(state):
if isInExplored(explored,child) == False and isInExplored(frontier,child) == False:
frontier.append(child)
level.append(currentLevel + 1)
parent.append(len(explored)-1)
print len(explored)


main()