The Towers of Hanoi

You may have heard of this logic puzzle involving three vertical pegs and a some disks of various sizes. All disks start on the same peg, arranged in order of size, biggest on the bottom. The object is to move all the disks to another peg, but you can move only one disk at a time, and you must never place a larger disk on top of a smaller one.

It's extremely difficult to solve the Towers problem if you don't think recursively. One of the legends about the puzzle is that a despot, faced with solving it, called in a close advisor who was supposed to be pretty smart, and asked for his help. The advisor said, “Oh, that's easy; to move seven disks from the first peg to the last, first move the top six disks to the middle peg, then ...

Get Sams Teach Yourself Ruby in 21 Days now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.