Hanoi Tower programming challenge...

Geoff Canyon gcanyon at gmail.com
Fri Jul 20 02:48:31 EDT 2012


Just for kicks I memo-ized this with a local variable. It dramatically
reduces the level of recursion and speeds up the calculation for large
towers. For example, calculating a twenty-disk tower goes from over
2,000,000 calls to tower() to 109, and the time is less than 1/3. I'm
actually surprised it's not faster. I'm curious if I'm missing something
obvious.

gc


*local* R

*on* mouseUp

   *ask* "How many disks are there?"

   *delete* variable R

   *put* tower (it , "A", "B" , "C") into field 2

*end* mouseUp

*
*

*function* tower N, *start*, destination, spare

   *if* R[N,*start*,destination,spare] is empty *then*

      *if* N = 1 *then* *put* "Move " & N & " from "& *start* & " to "&
destination & cr into R[N,*start*,destination,spare] *else* *put* tower(N -
1, *start*, spare, destination) &  "Move " & N & " from "& *start* & " to "&
destination & cr & tower(N - 1, spare, destination, *start*) into R[N,*start
*,destination,spare]

   *end* *if*

   *return* R[N,*start*,destination,spare]

*end* tower



More information about the use-livecode mailing list