def hanoi_iterative(num_disks, src, dest, aux):
#counting number of intructions for the polynomial complexity
num_moves = 2**num_disks - 1 #this line counts as 2 instructions
if num_disks % 2 == 0:
dest, aux = aux, dest
pegs = {src: [], dest: [], aux: []}
for i in range(num_disks, 0, -1):
pegs[src].append(i)
for _ in range(num_moves):
for peg1, peg2 in [(src, dest), (src, aux), (dest, aux)]:
if pegs[peg1] and (not pegs[peg2] or pegs[peg1][-1] < pegs[peg2][-1]):
pegs[peg2].append(pegs[peg1].pop())
hanoi iterative polynomial complexity for the worst case is when the number of rods is at least the number of disks, as it generates a perfect binary tree
O(2^n)
#polynomio para o hanoi iterativo: 2 + 22 +... + 2n = 2^2 * 2^n/2 + 2^2 * 2^(n-1)/2 +... + 2^2 * 2^0/2 = 2^(n+1)
hanoi recursive function: it takes the number of disks, the source rod, the destination rod, and the auxiliary rod as arguments.
def hanoi_recursive(num_disks,src,dest,aux):
# if there is only one disk, then move it from the source rod to the destination rod
if num_disks == 1:
push(src+" "+dest)
else:
# move the top n−1 disks from the source rod to the auxiliary rod
hanoi_recursive(num_disks - 1, src, aux, dest)
# move the nth disk from the source rod to the destination rod
hanoi_recursive(1, src, dest, aux)
# move the top n-1 disks from the auxiliary rod to the destination rod
hanoi_recursive(num_disks - 1, aux, dest, src)
hanoi recursive polynomial complexity for the worst case is when the number of rods is at least the number of disks, as it generates a perfect binary tree
O(2^n)
#polynomio para o hanoi recursivo: 2 + 22 +... + 2n = 2^2 * 2^n/2 + 2^2 * 2^(n-1)/2 +... + 2^2 * 2^0/2 = 2^(n+1)
Assistant
O polinômio para o hanoi iterativo é 2^(n+1) e o para o hanoi recursivo é também 2^(n+1).
O código parece estar correto, a função hanoi_iterative está implementando o algoritmo Hanoi iterativamente com complexidade de O(2^n) e a função hanoi_recursive está implementando o algoritmo Hanoi recursivamente com complexidade de O(2^n).
Ao comparar as duas funções, a recursiva é mais eficiente quando o tamanho do problema é pequeno, já a iterativa é mais eficiente quando o tamanho do problema é grande.