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
- Move n-1 aside, move the largest, then move n-1 back.
- The move count doubles with each extra disc.
- The out-parameter counts the moves without printing them.
Keywords and builtins used here
charhanoiifintmoves_forreturnvoid
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.
Step 7 of 7 in Functions, step 21 of 35 in Language basics.