Tower Of Hanoi - Solving Halfway Algorithm in Python

拈花ヽ惹草 提交于 2021-02-04 20:02:00

问题


Is it possible to solve tower of hanoi halfway? I've done extensive research to look for codes that solves the user's configuration halfway but I've yet to find one. This is for an assignment and I require the code to take over from where the user has stopped solving and continue solving it for the user, without resetting the puzzle to square one.

I understand that there are recursion algorithms out there readily available but that is not what I'm searching for. I'm searching for algorithms that can take over from where the user has solved until, and then continue solving from there. Any ideas?

So far, I've come up with an algorithm that stores the optimized algorithms( which is being done by recursion) into an array, and then checks if the user's input is equal to any found in the array, and then continue solving from there. However, the problem lies when the user's configuration is not found in the optimized algorithm array.

The following are my codes so far ( I've excluded the stack.py codes):

def solveHalfway(n, start, end, middle, count):
    gameInstance.stackA = [3,2]
    gameInstance.stackB = []
    gameInstance.stackC = [1]
    loopCounter = 0 # initialise loopCounter as 0
    moveCounter = 0 # initialise the move index the user is stuck at
    indicator = 0 # to indicate whether the user's config equals the solution's config
    while loopCounter < arrayOfStacks.size(): # while loopCounter size has not reached the end of arrayOfStacks
        if loopCounter != 0 and loopCounter % 3 == 0:  # if 3 stacks have been dequeued
            moveCounter += 1
            if gameInstance.getUserConfig() == tempStack.data:  #check whether user's config is equal to the solution's config
                indicator += 1
                print "User is stuck at move: ", moveCounter  #this will be the current move the user is at
                while arrayOfStacks.size() != 0: # while not the end of arrayOfStacks
                    correctMovesStack.push(arrayOfStacks.dequeue())  # add the moves to correctMovesStack
                    if correctMovesStack.size() == 3: # if 3 stacks have been dequeued
                        print "Step:", moveCounter , correctMovesStack.data # display the step number plus the correct move to take
                        moveCounter+=1 # increase move by 1
                        while correctMovesStack.size() != 0: # if correct moves stack isn't empty
                            correctMovesStack.pop() # empty the stack
                return
            else:
                while tempStack.size() != 0: # check if tempStack is empty
                    tempStack.pop()  # empty tempStack so that it can be used for the next loop
            tempStack.push(arrayOfStacks.dequeue()) #dequeue from arrayOfStacks for a total of 3 times and push it to tempStack
        else:
            tempStack.push(arrayOfStacks.dequeue()) #dequeue from arrayOfStacks for a total of 3 times and push it to tempStack
        loopCounter +=1 # increase loop counter by 1
    if indicator == 0:
        moveWith3Towers(noOfDisks, stackA, stackC, stackB, count)
    print indicator

回答1:


To solve the Towers of Hanoi from an arbitrary position, you can use a recursive procedure similar to the standard solution that works from the standard start position.

It just has to be a little more general.

Write a recursive procedure moveDisks(maxSize,targetPeg) that moves all the disks with size <= maxSize to the peg targetPeg, like this:

  1. Find the largest disk m such that m.size <= maxSize and m is not on targetPeg. If there is no such disk, then return, because all the disks with size <= maxSize are already in the right place.

  2. Let sourcePeg be the peg where m is currently, and let otherPeg be the the peg that isn't sourcePeg or targetPeg.

  3. Call moveDisks(m.size-1, otherPeg) recursively to get the smaller disks out of the way.

  4. Move m from sourcePeg to targetPeg.

  5. Call moveDisks(m.size-1, targetPeg) recursively to put the smaller disks where they belong.

In python, I would write it like this. Note that I used a different representation for the game state that works better for this algorithm and doesn't allow any illegal positions:

#
# Solve Towers of Hanoi from arbitrary position
#
# diskPostions -- the current peg for each disk (0, 1, or 2) in decreasing
#                 order of size.  This will be modified
# largestToMove -- move this one and all smaller disks
# targetPeg -- target peg for disks to move
#
def moveDisks(diskPositions, largestToMove, targetPeg):
    for badDisk in range(largestToMove, len(diskPositions)):

        currentPeg = diskPositions[badDisk]         
        if currentPeg != targetPeg:
            #found the largest disk on the wrong peg

            #sum of the peg numbers is 3, so to find the other one...
            otherPeg = 3 - targetPeg - currentPeg

            #before we can move badDisk, we have get the smaller ones out of the way
            moveDisks(diskPositions, badDisk+1, otherPeg)

            print "Move ", badDisk, " from ", currentPeg, " to ", targetPeg
            diskPositions[badDisk]=targetPeg

            #now we can put the smaller ones in the right place
            moveDisks(diskPositions, badDisk+1, targetPeg)

            break;

Test:

> moveDisks([2,1,0,2], 0, 2)
Move  3  from  2  to  0
Move  1  from  1  to  2
Move  3  from  0  to  1
Move  2  from  0  to  2
Move  3  from  1  to  2


来源:https://stackoverflow.com/questions/49220476/tower-of-hanoi-solving-halfway-algorithm-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!