Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # Sat Jul 4 15:09:13 BRT 2015
- # [hanoianimado.py]
- # Execucao:
- # $ python hanoianimado.py
- #
- # Desenha as hastes na tela.
- def Desenha(hastes, base):
- linhas = []
- for h in hastes:
- linha = []
- for z in h:
- if z == 0:
- e = ' ' * ((base-1)/2)
- e += '|'
- e += ' ' * ((base-1)/2)
- if len(e) < base:
- e = e + ' ' * (base - len(e))
- linha.append(e)
- else:
- e = ' ' * ((base-z)/2)
- e += 'o' * z
- e += ' ' * ((base-z)/2)
- if len(e) < base:
- e = e + ' ' * (base - len(e))
- linha.append(e)
- linha.append('*' * base)
- linhas.append(linha)
- for z in zip(*linhas):
- for s in z:
- print s,
- print
- #
- # MAIN
- #
- n = int(raw_input('Digite o numero de discos: '))
- h = int(raw_input('Digite a haste de origem (1, 2, 3): '))
- hastes = []
- discos = [ 2*i for i in range(2,n+2) ]
- base = max(discos) + 2
- # Realiza permutacao de nomes. O algoritmo original somente
- # considera 0 como inicial. Logo, se escolher h=2 entao
- # considera o novo zero a haste 2 (posicao 1).
- NOMES = []
- if h == 1:
- NOMES = [0, 1, 2]
- elif h == 2:
- NOMES = [1, 0, 2]
- else:
- NOMES = [2, 0, 1]
- # Preenche inicialmente as hastes
- for i in range(1, 4):
- if i == h:
- hastes.append([0] + discos)
- else:
- hastes.append([0] + [ 0 for i in range(n) ])
- movimentos = 1
- for i in range(2**n):
- # Manda desenhar
- Desenha(hastes, base)
- k = i+1
- # obtem haste origem
- origem = NOMES[(k&(k-1))%3] ;
- # obtem haste destino
- destino = NOMES[((k|(k-1))+1)%3] ;
- print
- print "Mova disco de %d para %d (%d movimentos)" % (origem+1, destino+1, movimentos) ;
- #
- # Descreve o movimento
- #
- (j, o) = (0, 0)
- # Obtem index do elemento no topo da haste origem (em o)
- for h in hastes[origem]:
- # h : disco no topo
- if h != 0:
- o = j
- break
- j += 1
- d=0
- j=len(hastes[destino])-1
- # Obtem index do elemento no topo da haste origem (em d)
- for h in reversed(hastes[destino]):
- if h == 0:
- d = j
- break
- j -= 1
- if d == 0: d = len(hastes[destino])-1
- # Realiza a permutacao de discos
- hastes[destino][d] = hastes[origem][o]
- hastes[origem][o] = 0
- raw_input('\nPressione ENTER...')
- movimentos += 1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement