trouble with tower of Hanoi variant where the number of pegs = number of disks + 1

114 Views Asked by At

I'm trying to implement a variant of the tower of Hanoi in python. The rules are the same as the original game but also you can only move a disk one peg to the right or left, and the number of pegs = number of disks + 1. I saw this geeks for geeks article explained how to do it with 3 pegs here: https://www.geeksforgeeks.org/twisted-tower-of-hanoi-problem/ Below is my flawed implementation followed by the printout from running it.

def twistedTOH(n,first,last):
        
    # Base case
    if (n == 1):
        print("Move disk ###", n, "from rod", first,
              "to",last)
        return

    # Move disk 1 from first peg to last peg
    twistedTOH(n - 1,first, last ) 

    # Move n-1 disks as far right as legal
    y = last-1 # In order to move n disks
    z = n #to keep track of how many moved, should be 1
    while(y > 1):
    
        print("Move disk ---", z, "from rod", first, "to", y)
        z = z + 1
        y = y-1
    # Move n-1 disks from last to first
    twistedTOH(n - 1, last, first)

    # Move nth disk from middle to last
    y = last
    z = n
    
    while(y > 2):
        print("Move disk &&&", z, 'right one', "to", y)
        z = z + 1
        y = y-1
        
    twistedTOH(n - 1, first,last)

The printout from running this is

Move disk ### 1 from rod 1 to 4
Move disk --- 2 from rod 1 to 3
Move disk --- 3 from rod 1 to 2
Move disk ### 1 from rod 4 to 1
Move disk &&& 2 right one to 4
Move disk &&& 3 right one to 3
Move disk ### 1 from rod 1 to 4
Move disk --- 3 from rod 1 to 3
Move disk --- 4 from rod 1 to 2
Move disk ### 1 from rod 4 to 1
Move disk ### 1 from rod 1 to 4
Move disk ### 1 from rod 4 to 1
Move disk &&& 3 right one to 4
Move disk &&& 4 right one to 3
Move disk ### 1 from rod 1 to 4
Move disk --- 2 from rod 1 to 3
Move disk --- 3 from rod 1 to 2
Move disk ### 1 from rod 4 to 1
Move disk &&& 2 right one to 4
Move disk &&& 3 right one to 3
Move disk ### 1 from rod 1 to 4

After the 2nd loop all the disks should be shifted right 1, after the smallest disk is placed at the first peg. This is where I'm failing to implement. Now I want to to shift the disk on the last peg to the peg corresponding with its disk number, but I can't seem to figure that part out. I've tried looping it but because of the recursive call I can't get it to work. Any help would be appreciated.

0

There are 0 best solutions below