py
def hanoinoto(hanoi, n):
"""Tower of Hanoi display"""
print('------', n)
for stack in hanoi:
print('#', ''.join(stack))
N = 3 #Number of disks
#State of the disk at three positions
hanoi = [list('4321')[-N:], [], []]
hanoinoto(hanoi, 0) #Initial state display
#Move all discs
for n in range(1, 2**N):
i = (n & (n - 1)) % 3 #Move source (bit operation)
j = ((n | (n - 1)) + 1) % 3 #Move destination (bit operation)
c = hanoi[i].pop() #Pop from position i
hanoi[j].append(c) #Append to position j(push)
hanoinoto(hanoi, n)
Execution result
------ 0 # 321 # # ------ 1 # 32 # # 1 ------ 2 # 3 # 2 # 1 ------ 3 # 3 # 21 # ------ 4 # # 21 # 3 ------ 5 # 1 # 2 # 3 ------ 6 # 1 # # 32 ------ 7 # # # 321
Recommended Posts