This isn’t a typical tutorial where I walk through the building of a program. I was just curious how a C++ Tower of Hanoi solver translates to Snap! I can report that it translates very well. In fact, I prefer the Snap! version because the results are paired with a nice visual, making it easy to follow along.
You can find the C++ code and its Snap! equivalent below. First, a quick explanation of the game.
Tower of Hanoi is a mathematical puzzle. It consists of three rods and a number of disks of different sizes, which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top.
The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:
- Only one disk can be moved at a time.
- Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack or on an empty rod.
- No disk may be placed on top of a smaller disk.
With 3 disks, the puzzle can be solved in 7 moves. The minimal number of moves required to solve a Tower of Hanoi puzzle is 2n − 1, where n is the number of disks.
The C++ program uses a recursive function.
Wikipedia page for Tower of Hanoi. It’s an interesting read and covers the recursive, non-recursive, binary, and gray-code solutions.
I named my function moveDisks and it takes in 4 variables. n denotes the number of disks while fromTower, toTower, and auxTower denote the rods.
Pretty straightforward and the results work. But wouldn’t the results be a bit more appealing in Snap! form?
Snap! (BYOB) Solver
This version follows the same recipe as the C++ code. I made a custom block, added my variables, inserted an if else statement, created my base case, then used recursion to work through the puzzle.
The custom block:
Where the magic happens:
I used blocks from the following categories:
In actual game play, these are the movements (L to R):
If you’d like to play Tower of Hanoi, here are a few links:
That’s all there is to it! The Tower of Hanoi solver demonstrates that even a simple algorithm can be quite powerful. How long would it take to solve a 15 disk run without the solver’s help?
Watch the video below to see a 15 disk run in C++.