I’ve got an interview coming up in the next couple of weeks for a fairly large software company. Something that’s regarded as a bit of a classic problem is the Towers Of Hanoi puzzle. The story goes something like this:
There is a history about an Indian temple in Kashi Vishwanath which contains a large room with three time-worn posts in it surrounded by 64 golden disks. Brahmin priests, acting out the command of an ancient prophecy, have been moving these disks, in accordance with the immutable rules of the Brahma, since that time. According to the legend, when the last move of the puzzle will be completed, the world will end. (Wikipedia)
The “immutable rules of the Brahma” are:
- Only one disk may be moved at a time.
- Each move consists of taking the upper disk from one of the rods and sliding it onto another rod, on top of the other disks that may already be present on that rod.
- No disk may be placed on top of a smaller disk.
You can actually buy these as children’s toys, and the thing is, kids start to pick it up pretty quickly. There’s a pattern to it, and there’s only one way of doing it, so it’s something that’s easy to learn intuitively. It’s a little bit harder to codify, however. Here’s the solution I came up with:
- Start with all of the discs on pillar A.
- To move all the discs to pillar B:
- Move the stack of discs less the bottom disc to pillar C
- Move the last disc to pillar B
- Move the stack of discs on pillar C back to pillar B.
You’ll notice that this is a recursive solution – it works out to only be a few lines of code. Here’s what I came up with:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Whilst the algorithm wasn’t too bad, I found setting up the infrastructure
fairly difficult. I was using my own custom
Stack implementation (another
practice question), and printing stacks is either destructive and O(n) or an
O(2n) operation (copy all the elements to one stack, then copy them back). So,
I needed a copy constructor that copied the linked list internal to the stack.
Headache! The other little bit of trickery here is the
function: because we’re swapping s1, s2, and s3 on each recursion, we can’t
just print s1, s2, and s3 per-se. Here’s the function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
What we’re doing here is:
- Saving pointers to s1, s2, and s3 when we call with non-default parameters, and then
- Copying the stacks on every call,
- Then destructively removing and printing elements from all the stacks.
You can find my full working code for this solution (including a linked-list implementation, and a stack implementation) at my github exercises repo.