• API
• FAQ
• Tools
• Archive
daily pastebin goal
51%
SHARE
TWEET

Untitled

a guest May 16th, 2018 102 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:
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)
37.     li \$v0, 10
38.     syscall
39.
40. hanoi:
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)
62.     jr \$ra
63. base_case:
65.     sw \$ra, 0(\$sp)
66.
67.     jal print
68.
69.     lw \$ra, 0(\$sp)
71.     jr \$ra
72. print:
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)