Towers of Hanoi
Towers of Hanoi
[Christopher’s code]
[Christopher’s code]
State is list of number of disks on each peg....
In[]:=
moves[state_,pegs_]:=Catenate@MapIndexed[Function[{p,i},With[{smallerDisks=Drop[state,i[[1]]]},If[MemberQ[smallerDisks,p],{},ReplacePart[state,i#]&/@Complement[Range[pegs],smallerDisks,{p}]]]],state]
In[]:=
hanoiGraph[pegs_,disks_]:=Graph[DeleteDuplicatesBy[Catenate[Function[s,s#&/@moves[s,pegs]]/@Tuples[Range[pegs],disks]],Sort]]
In[]:=
moves[{1,2,1},5]
Out[]=
{{1,3,1},{1,4,1},{1,5,1},{1,2,2},{1,2,3},{1,2,4},{1,2,5}}
In[]:=
Graph[hanoiGraph[3,3],VertexLabelsAutomatic]
Out[]=
For successive disks, say which peg they are on:
{3,3,1,1}
You can sort the disks on any given peg.....
In[]:=
graphtower[n_,li_]:=Module[{y=-2},Graphics[{{LightBlue,Rectangle[{-.4,0},{.4,2n+1}]},Map[(y=y+2;{EdgeForm[{Black,Thickness[.025]}],LightGreen,Rectangle[{-2#+.6,y+.05},{2#-.6,y+2}]})&,Reverse[li]]},PlotRange->{{-2n,2n},{0,2n+1}},AspectRatio1,ImageSize40]]
In[]:=
graphtower[4,{3,2,1}]
Out[]=
In[]:=
TowerDisplay[list_,pegs_]:=GraphicsRow[graphtower[Length[list],#]&/@Table[Sort[Flatten[Position[list,i]]],{i,pegs}]]
In[]:=
TowerDisplay[{1,1,1},3]
Out[]=
[[ The following is not correct somehow.... the largest disk, rather than smallest, seems to be moving ]]
In[]:=
Graph[hanoiGraph[3,3],VertexLabels(#Placed[Framed[TowerDisplay[#,3]],Center]&/@VertexList[hanoiGraph[3,3]])]
Out[]=