5.51 · exercise

Tower of Hanoi

Three pegs, A, B and C, and a tower of n discs on peg A, the smallest on top. Move the whole tower to peg C one disc at a time, never putting a bigger disc on a smaller one. The starter's main reads n (0 to 10) and calls hanoi(n, 'A', 'C', 'B'). Write hanoi so it prints every move and returns how many moves it made.

hanoi is recursive: it calls itself on a smaller tower. To move n discs from from to to, move the top n - 1 discs from from to spare, move disc n from from to to, then move the n - 1 discs from spare to to. A tower of 0 discs needs no moves. Print the move of disc d as disc d: X -> Y, with the pegs printed as characters (%c).

Every call of hanoi still needs n, the three pegs, and its running count after its own calls return, so keep them in x19 to x28. Its caller is using those registers too, so save the ones you use in the frame on entry and restore them before ret.

For n = 2 the output is:

disc 1: A -> B
disc 2: A -> C
disc 1: B -> C
moves: 3

What is checked

  • every move, then the count, for the starter's input (n = 3)
  • the program exits with status 0
  • the same checks on other inputs the checker keeps hidden, including an empty tower

specification

stdin3
stdoutprints the right output
exitexits with the right code
sourceuses bl hanoi in hanoi
hiddenright output and exit code on 4 more inputs you do not see

We run your program on the input above and on the hidden ones, and compare what it does. Nothing is matched against a stored solution.

loading editor...

regfile

N clearZ clearC clearV clear

x0–x30 are the integer registers.

X0arg00x0000000000000000
X1arg10x0000000000000000
X2arg20x0000000000000000
X3arg30x0000000000000000
X4arg40x0000000000000000
X5arg50x0000000000000000
X6arg60x0000000000000000
X7arg70x0000000000000000
X8ind0x0000000000000000
X90x0000000000000000
X100x0000000000000000
X110x0000000000000000
X120x0000000000000000
X130x0000000000000000
X140x0000000000000000
X150x0000000000000000
X16ip00x0000000000000000
X17ip10x0000000000000000
X18pr0x0000000000000000
X190x0000000000000000
X200x0000000000000000
X210x0000000000000000
X220x0000000000000000
X230x0000000000000000
X240x0000000000000000
X250x0000000000000000
X260x0000000000000000
X270x0000000000000000
X280x0000000000000000
X29fp0x0000000000000000
X30lr0x0000000000000000
SP0x0000000080000000
PC0x0000000000400000
console

Output prints here as your program runs.

Press step or run under the editor, or feed stdin from the box below.

not assembled

Open in playground