![]() Note that this is going to be much slower than the version that does not need to find the actual solution (this being codereview maybe some folks have suggestions to make it run faster) Move_list = LHSMoves + MyMoves + RHSMoves ![]() If any(move is None for move in ):continue #bad path :( RHSMoves = FrameStewartSolution(kdisks,helper_pegs,end,pegs)#move the intermediat stack to MyMoves = FrameStewartSolution(ndisks-kdisks,start,end,pegs_for_my_moves) #misleading variable name but meh Pegs_for_my_moves = pegs.difference(]) # cant use the peg our LHS stack is sitting on LHSMoves = FrameStewartSolution(kdisks,start,helper_pegs,pegs) If len(pegs) = 3:#3 pegs is well defined optimal solution of 2^n-1 If ndisks = 1 and len(pegs) > 1: #if there is only 1 disk it will only take one move If ndisks =0 or start = end: #zero disks require zero moves You can easily verify that this is returning optimal solutions by knowing that the optimal solution to the towers of hanoi with 3 pegs is 2 ndisks - 1Īll thats left is to change FrameStewart to also return moves def FrameStewartSolution(ndisks,start=1,end=4,pegs=set()): Return moves_to_my_move + + moves_after_my_move Moves_after_my_move = towers3(ndisks-1,helper_peg,target) Moves_to_my_move = towers3(ndisks-1,start,helper_peg) If ndisks = 1: #trivial case if there is only one disk, just move it If ndisks = 0 or start = target: #if there are no disks, or no move to make Start by solving the towersofhanoi with 3 pegs as that is the traditional layout and has well defined algorithms to solve def towers3(ndisks,start=1,target=3,peg_set=set()): If you actually need the moves you will have to heavily modify this solution. This tells us that the optimal solution for 16 disks and 4 pegs is 161 moves, note that it does not tell us what those moves are #all other cases where there is no solution (namely one peg, or 2 pegs and more than 1 disk) Return min(potential_solutions) #the best solution Potential_solutions = (2*FrameStewart(kdisks,npegs) + FrameStewart(ndisks-kdisks,npegs-1) for kdisks in range(1,ndisks)) If npegs = 3:#3 pegs is well defined optimal solution of 2^n-1 If ndisks = 1 and npegs > 1: #if there is only 1 disk it will only take one move If ndisks =0: #zero disks require zero moves ![]() This builds up a solution to the number of moves to achieve a solution. If you are just trying to find the minimum number of moves and not necessarily a solution you can use the Frame–Stewart algorithm that you linked to earlier
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |