liveBook · Manning

Towers of Hanoi puzzle

As explained in Classic Computer Science Problems in Swift: Essential techniques for practicing programmers

A mathematical puzzle involving moving a stack of differently sized discs between three pegs while allowing one disc at a time and forbidding wider discs from resting on narrower discs.

The Towers of Hanoi asks you to move a stack of differently sized discs from tower A to tower C, one disc at a time, without placing a wider disc on a narrower one. section 1.5

Model each tower as a stack: push adds a disc, and pop removes the top disc. Swift’s Array provides the backing store for this LIFO structure. section 1.5

A recursive solution separates the task into two cases:

  • Base case: move one disc directly from the source tower to the destination. section 1.5
  • Recursive case: move the upper n−1 discs to the temporary tower, move the remaining disc, then move the n−1 discs onto the destination. section 1.5
  • The same procedure can be reused for the smaller subproblems, while the stack operations preserve legal move order. section 1.5

Three discs from A to C

Move the top disc from A to C, the middle disc from A to B, and the top disc from C to B. Move the bottom disc from A to C, then repeat the two-disc procedure from B to C. section 1.5

Figure 1.7. The challenge is to move the three discs, one at a time, from tower A to tower C. A larger disc may never be on top of a smaller disc.

Use the diagram to track the three discs, their source and destination towers, and the rule that larger discs cannot rest on smaller ones. section 1.5

How Classic Computer Science Problems in Swift: Essential techniques for practicing programmers covers it

How deep it goes
Develops stack modeling, base and recursive cases, and a three-disc walkthrough with executable Swift functions.
Examples
Uses three discs, towers A–C, Swift Stack values, and a recursive hanoi function as concrete artifacts.
What it assumes
Assumes familiarity with Swift functions and arrays while introducing stacks through push and pop operations.
What you can do after
Build it from scratch by representing towers as stacks and implementing the recursive Swift solver.
How it connects
Connects recursion with stacks, LIFO operations, Swift arrays, and unit testing through an extension exercise.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Classic Computer Science Problems in Swift: Essential techniques for practicing programmers. The section links point to the parts of the book it draws on.