daily pastebin goal
2%
SHARE
TWEET

Untitled

a guest May 16th, 2018 101 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod)
  2. {
  3.     if (n == 1)
  4.     {
  5.         printf("n Move disk 1 from rod %c to rod %c", from_rod, to_rod);
  6.         return;
  7.     }
  8.     towerOfHanoi(n-1, from_rod, aux_rod, to_rod);
  9.     printf("n Move disk %d from rod %c to rod %c", n, from_rod, to_rod);
  10.     towerOfHanoi(n-1, aux_rod, to_rod, from_rod);
  11. }
  12.  
  13. int main()
  14. {
  15.     int n = 4; // Number of disks
  16.     towerOfHanoi(n, 'A', 'C', 'B');  // A, B and C are names of rods
  17.     return 0;
  18. }
  19.    
  20. .globl main
  21. main:
  22.     addi $sp, $sp, -4
  23.     sw $ra, 0($sp)
  24.  
  25.     li $v0, 5 # system call code for read_int
  26.     syscall
  27.  
  28.     move $a0, $v0 # a0 holds the number of disks
  29.     li $a1, 'A' # a1 holds from_rod
  30.     li $a2, 'C' # a2 holds to_rod
  31.     li $a3, 'B' # a3 holds aux_rod
  32.  
  33.     jal hanoi
  34.  
  35.     lw $ra, 0($sp)
  36.     addi $sp, $sp, 4
  37.     li $v0, 10
  38.     syscall
  39.  
  40. hanoi:
  41.     addi $sp, $sp, -4
  42.     sw $ra, 0($sp)
  43.  
  44.     beq $a0, 1, base_case
  45.     addi $a0, $a0, -1 # number_of_disks -= 1
  46.     # swap between to_rod and aux_rod :
  47.     move $t0, $a2 # temp = to_rod
  48.     move $a2, $a3 # to_rod = aux_rod
  49.     move $a3, $t0 # aux_rod = temp
  50.     jal hanoi
  51.  
  52.     jal print
  53.  
  54.     # swap between from_rod and aux_rod :
  55.     move $t0, $a1 # temp = from_rod
  56.     move $a1, $a3 # from_rod = aux_rod
  57.     move $a3, $t0 # aux_rod = temp
  58.     jal hanoi
  59.  
  60.     lw $ra, 0($sp)
  61.     addi $sp, $sp, 4
  62.     jr $ra
  63. base_case:
  64.     addi $sp, $sp, -4
  65.     sw $ra, 0($sp)
  66.  
  67.     jal print
  68.  
  69.     lw $ra, 0($sp)
  70.     addi $sp, $sp, 4
  71.     jr $ra
  72. print:
  73.     addi $sp, $sp, -4
  74.     sw $ra, 0($sp)
  75.     move $t0, $a0
  76.  
  77.     li $v0, 11
  78.     move $a0, $a1
  79.     syscall # print from_rod
  80.     li $a0, '>'
  81.     syscall # print the char '>'
  82.     move $a0, $a2
  83.     syscall # print  to_rod
  84.     li $a0, 'n'
  85.     syscall # pirnt new line
  86.     move $a0, $t0
  87.  
  88.     lw $ra, 0($sp)
  89.     addi $sp, $sp, 4
  90.     jr $ra
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top