Calum Knott

I'm currently employed by Didactic Services, a FESTO Partner, as a Senior Applications Engineer.
I'm currently the WorldSkillsUK Mechatronics Training Manager
I'm also a Visiting Lecturer at Middlesex University
Occasionally I can be persuaded to Freelance!

Contact Me

These posts are archived
They were written with an old blogging platform, and are no longer really maintainable, however as they are linked too from various pages on the web - it seemed a good idea to try and archive them. I have written just enough code to get them to display - but there will probably be a few broken links and images.
Any major queries - feel free to contact me

Towers of Hanoi

17 / 6 / 2014

The tower of Hanoi is a mathmatical puzzle that is fairly well known. In it, they player must attempt to move the tower across three pillars, but can only move the rings under certain strict conditions:

1. Smaller rings must always be ontop of larger rings. (never the other way round)
2. Only the top ring on each pillar can be moved
3. Only one ring can be moved at a time

Towers Of Hanoi

These conditions make the game a fun challenge.

It is possible to solve the puzzle in: 2^n - 1 moves, where n is the number of rings.

A good solution for the towers can be found by following a routine:

Even number of rings:
A <-> B
A <-> C
B <-> C

Odd number of rings:
A <-> B
A <-> C
B <-> C

Note, that the ring is always moved so the smallest is placed on the biggest


My final code for this project will be in a different language, but for now i wanted to try and write a python based solution, partly for fun, and partly to think about data structures.

I came across a post aimed at teaching recursive programming using python that solved the problem very effectivly.
Their solution, used recursive calls to solve the tower.

Their Code

It is beautiful code, that solves the towers in just 11 lines of python, however getting your head around the recursion is quite painful.
Additionally, their code uses objects (combined strings and arrays with names) which i know is not an option in my final chosen language
It also uses a python quirk to check for empty arrays, my version uses a fairly stndard try catch method.

And so I decided to write a longer, but slightly friendlier version.

Essentially, my version utilises three Arrays, A, B & C.
The tower starts on A
1 = biggest ring

While the tower is not fully on C, the swaps are made.

My Code

This wont be useful to everyone, but it was for me :)