Search code examples
recursiontowers-of-hanoi

tower of hanoi initial configuration?


I am reading the code my friend wrote for his tower of hanoi solution. But it's hard for me to figure out what his code does since I don't understand his init configuration and ending configuration .

def T(init, final):
    if len(init) == 0:
        return 
    if init[0] == final[0]:
        T(init[1:], final[1:])
    else:
        fro = init[0]
        to = final[0]
        spare = other(init[0], final[0])
        ic = spare * (len(init) - 1)
        T(init[1:], ic)
        print("move from %s to %s  " % (fro, to))
        T(ic, final[1:])

def other(char1, char2):
    towers = "ABC"
    towers = towers.replace(char1, "")
    towers = towers.replace(char2, "")
    return towers

init = "ABCBA"
final = "BCBAC"
T(init, final)

Here, he has init = "ABCBA" and final = "BCBAC". The code works fine but I don't get why he is doing this.

Any help is appreciated.


Solution

  • init and final configurations are just the order of disks' size from large to small and their respective rod, denoted as a letter (A, B or C in this case).

    init = "ABCBA" is when you have largest disk at 'A', second largest at 'B', third largest at 'C' and so on.

    Say, you have

    init = "AB"
    final = "AA"
    

    the program would output

    move from B to A  
    

    since you have the smaller disk sitting at B, all you have to do is to move it to A to obtain AA.