Assembly代写:CS2036 Towers of Hanoi

将C语言的汉诺塔程序,用汇编语言改写。

Requirement

A famous problem in Computer Science is the Towers of Hanoi problem.

In this problem you have N disks and 3 pegs. You can move only one disk at a time and a disk cannot be stacked on a disk smaller than itself. So, to move the top two disks to peg 2, you would have to move the top disk to peg 3, the next disk to peg 2, then that disk from peg three to peg 2.

What makes this problem interesting is that is has a very simple recursive solution. Here’s a C program that solves the Tower of Hanoi problem:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <stdio.h>
#include <stdlib.h>

void towers(int, int, int, int);

int main()
{

char buffer[20];
int num;

printf("Enter the number of disks: ");
fgets(buffer, sizeof(buffer), stdin);
num = atoi(buffer);
if (num < 1)
{
printf("Towers of Hanoi makes no sense with %d disks\n", num);
return 1;
}

printf("The moves to solve the Tower of Hanio are:\n");
towers(num, 1, 2, 3);
return 0;
}

/**
* Recursive function that moves num pegs from
* frompeg to topeg using auxpeg as an intermediate
* storage location.
*/

void towers(int num, int frompeg, int topeg, int auxpeg)
{

if (num == 1)
{
printf("Move disk 1 from peg %d to peg %d\n", frompeg, topeg);
return;
}
towers(num - 1, frompeg, auxpeg, topeg);
printf("Move disk %d from peg %d to peg %d\n", num, frompeg, topeg);
towers(num - 1, auxpeg, topeg, frompeg);
}

Your task is to write an equivalent solution in assembly language. Create a directory named hanoi under system5 and put your solution in there. The program must be in one .S file named hanoi.S.