Damon Cortesi's blog

Musings of an entrepreneur.

Hanoi in Batch

| Comments

I stumbled across a post a couple days ago that challenged to solve the Hanoi problem using batch. Being a batch aficionado and scripting everything from IPSec policies and network configuration to remote VNC installs, I thought I would give it a shot.

The algorithm to solve the Hanoi problem is actually quite simple and with the exception of N-1 not being set properly the second time around, it was pretty easy to convert the pseudo-code to batch. To make it a little bit more challenging, I configured the script to be fairly dynamic in that it determines how many Hanoi disks there are and initializes it’s variables based on that. I am very much against writing scripts that you need to modify when an external factor has changed. My solution is available here: hanoi.bat

Being the overachiever that I am and driven by an odd desire to automate any manual process, I also whipped up another script to initialize the Hanoi disks. I actually did this prior to the hanoi script so I could easily build up and tear down the disk structure. Copy and paste was too much of a manual process for me. grin Again, allowing for my desire to make the script as dynamic as possible, I build the disks based on a pre-defined height. In addition, a desired height can be passed to the script as the first parameter, which makes it very easy to build a tower of any height. So if I want to build a tower of 100 disks and let my computer run through the 1.2676506 * 1030 iterations it would take to solve it, which I also just learned is the probability of tossing a coin and getting the same result 100 times in a row. The script is also configured to remove any previous disks. This init script is available here: init.bat

Thanks for the challenge, Adi. I had a good time with it!