Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download

Hanoi Towers

Views: 92
1+1
2
def Hanoi(S, f, t, n, snapshots=[]): if n==0: return other = [i for i in range(3) if i not in [f,t]][0] Hanoi(S,f,other, n-1, snapshots) S[t].append(S[f].pop()) snapshots.append(deepcopy(S)) Hanoi(S,other,t, n-1, snapshots) def HanoiProcess(n): initial = [range(n,0,-1),[],[]] snapshots = [[range(n,0,-1),[],[]]] Hanoi(initial,0,2,n,snapshots) return snapshots def draw_pegs(n): # vxs of pegs, other pegs are shifted by 2*(n+1) pole = [(n,0),(n+1,0),(n+1,n+1),(n,n+1)] # we begin by drawing the base background = polygon2d([(0,-2),(6*n+5,-2),(6*n+5,0),(0,0)],color='black') for i in range(3): #then we draw the pegs background += polygon2d([(a+2*i*(n+1),b) for a,b in pole],color='black') return background def draw_snapshot(s,n): snapshot = draw_pegs(n) for i,pole in enumerate(s): for h,r in enumerate(pole): # We can think of x as a measure of the disk size. x = float(r)/n # Based on the size of the disk we choose a color from the colormap red,gre,blu,dumm = colormaps.cool(x) # We draw the disk. Height from the base is measured by h. # Disk will be a 2r+1 x 1 rectangle centered about the peg and at height h. snapshot += polygon2d([(n+2*i*(n+1)-r,h),(n+2*i*(n+1)+r+1,h),(n+2*i*(n+1)+r+1,h+1),(n+2*i*(n+1)-r,h+1)],rgbcolor=(red,gre,blu)) return snapshot def HanoiPlots(n): snapshots = HanoiProcess(n) return [draw_snapshot(s,n) for s in snapshots] def HanoiAnimation(n): plots = HanoiPlots(n) return animate(plots, axes=False)
n=3 A=HanoiAnimation(5)
A.show(delay=100)
A.show(delay=0.1)
A.show(delay=0.5)
draw_snap([[8,7,6,5,4,3,2,1],[],[]],8).show(axes=False)
range(8,0,-1)
[8, 7, 6, 5, 4, 3, 2, 1]