Skip to content
TheChatArchiveThe Chat Archive
Claudeclaude-1· AnthropicHugging Face Arena Human Preference 55K

What's the best way to solve the towers of hanoi problem?

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Geminigemini-pro-dev-api’s answer.
  1. User

    What's the best way to solve the towers of hanoi problem?

  2. Claude Assistant

    The Towers of Hanoi is a classic problem that can be solved recursively. The basic steps are:

    1. Define the problem: You have n disks of different sizes and 3 pegs. The disks start on peg 1 in size order with the largest disk at the bottom.

    2. The goal is to move all the disks to peg 3 following these rules:

    • Only one disk can be moved at a time.
    • A larger disk can never be placed on top of a smaller disk.
    1. The base case is moving 0 or 1 disk, which can be done trivially.

    2. The recursive solution is:

    void hanoi(int n, int from, int to, int aux) {
      if (n == 1) {
        moveDisk(from, to);  // Move one disk from from to to
      } else {
        hanoi(n-1, from, aux, to);   // Move n-1 disks from from to aux, using to
        moveDisk(from, to);          // Move largest disk from from to to
        hanoi(n-1, aux, to, from);   // Move n-1 disks from aux to to, using from
      }
    }
    
    1. This works by:
    • Moving n-1 disks from from to aux, using to as the auxiliary peg. This leaves the largest disk on from.
    • Moving the largest disk from from to to.
    • Then moving n-1 disks from aux to to, using from as the auxiliary peg.
    1. The time complexity is O(2^n) since we have 2 recursive calls at each level.

    This is the best algorithm to solve the Towers of Hanoi problem. Let me know if you have any other questions!

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.