typestar

Towers of Hanoi in C

Recursion that moves a whole stack by trusting the smaller case.

void hanoi(int n, char from, char to, char via, int *moves) {
    if (n == 0) {
        return;
    }
    hanoi(n - 1, from, via, to, moves);
    (*moves)++;
    hanoi(n - 1, via, to, from, moves);
}

int moves_for(int discs) {
    int moves = 0;
    hanoi(discs, 'A', 'C', 'B', &moves);
    return moves;
}

How it works

  1. Move n-1 aside, move the largest, then move n-1 back.
  2. The move count doubles with each extra disc.
  3. The out-parameter counts the moves without printing them.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
267
Tokens
105
Three-star pace
90 tpm

At the three-star pace of 90 tokens a minute, this run takes about 70 seconds.

Type this snippet

Step 7 of 7 in Functions, step 21 of 35 in Language basics.

← Previous Next →