I would like to implement Hanoi Towers algorithm in MIPS assembly.
Rods are indicated by A
, B
and C
.
Input is number of number of disks and output is the sequence of moves necessary to solve the problem.
For example:
If input is 3
, output should be:
A>C
A>B
C>B
A>C
B>A
B>C
A>C
I've managed to get the result with the numbers of the rods, i.e. 1>3
instead of A>C
, with the following code:
.data
NewLine: .asciiz "\n"
To: .asciiz ">"
.globl main
.text
main:
li $v0, 5
syscall
add $a0, $v0, $zero
addi $a1, $zero, 1
addi $a2, $zero, 3
addi $a3, $zero, 2
jal hanoi1
li $v0, 10
syscall
hanoi1:
addi $t0, $a0, 0
addi $t1, $zero, 1
bne $a0, $t1, hanoi2
li $v0, 1
move $a0, $a1
syscall
li $v0, 4
la $a0, To
syscall
li $v0, 1
move $a0, $a2
syscall
li $v0, 4
la $a0, NewLine
syscall
addi $a0, $t0, 0
jr $ra
hanoi2:
addi $sp, $sp, -20
sw $ra, 16($sp)
sw $a3, 12($sp)
sw $a2, 8($sp)
sw $a1, 4($sp)
sw $a0, 0($sp)
addi $t3, $a3, 0
addi $a3, $a2, 0
addi $a2, $t3, 0
addi $a0, $a0, -1
jal hanoi1
lw $ra, 16($sp)
lw $a3, 12($sp)
lw $a2, 8($sp)
lw $a1, 4($sp)
lw $a0, 0($sp)
addi $t0, $a0, 0
addi $t1, $zero, 1
li $v0, 1
move $a0, $a1
syscall
li $v0, 4
la $a0, To
syscall
li $v0, 1
move $a0, $a2
syscall
li $v0, 4
la $a0, NewLine
syscall
addi $a0, $t0, 0
addi $t3, $a3, 0
addi $a3, $a1, 0
addi $a1, $t3, 0
addi $a0, $a0, -1
jal hanoi1
lw $ra, 16($sp)
addi $sp, $sp, 20
add $v0, $zero, $t5
jr $ra
I tried to add labels such as:
PrintA:
li $v0, 4
la $a0, A
syscall
jr $ra
And add beq
to branch to the right label:
beq $a1, $t7, PrintA # $t7=1
beq $a1, $t8, PrintB # $t8=2
beq $a1, $t9, PrintC # $t9=3
But the program got into infinite loop, probably because I didn't handle $ra
correctly.
So my problem is I can't figure out how to convert the rods numbers to letters.
Any help would be appreciated.