Velocity Reviews > very hard for me what is the way to solv ??

# very hard for me what is the way to solv ??

wahid
Guest
Posts: n/a

 01-10-2010
• The Tower of Hanoi or Towers of Hanoi is a
mathematical game or puzzle. It consists of three
rods, and a number of disks of different sizes
which can slide onto any rod.
• The objective of the puzzle is to move the entire
stack to another rod, obeying the following rules:
– Only one disk may be moved at a time.
– Each move consists of taking the upper disk from one
of the rods and sliding it onto another rod, on top of
the other disks that may already be present on that
rod.
– No disk may be placed on top of a smaller disk.

• Using recursion, write a program, that would
solve the tower of Hanoi Problem.
• Inputs: Number of Disks, Name of the three
pegs ( Peg on which initially all the disks rest is
input peg, peg on which finally all disks will lie
is output peg, the third peg is the other peg)

(Hint: think recursively, what if there were only two disks?
and what if the N-1 small disks where combined into a single disk?)

Sample Output:

Enter Input peg: 1
Enter output peg :2
Enter other peg : 3
Enter the number of disks :3
Tower of hanoi Solution :
Move Disk from Peg 1 to Peg 2
Move Disk from Peg 1 to Peg 3
Move Disk from Peg 2 to Peg 3
Move Disk from Peg 1 to Peg 2
Move Disk from Peg 3 to Peg 1
Move Disk from Peg 3 to Peg 2
Move Disk from Peg 1 to Peg 2

Antoninus Twink
Guest
Posts: n/a

 01-10-2010
On 10 Jan 2010 at 7:15, wahid wrote:
> â€¢ Using recursion, write a program, that would solve the tower of
> Hanoi Problem.
> â€¢ Inputs: Number of Disks, Name of the three pegs ( Peg on which
> initially all the disks rest is input peg, peg on which finally all
> disks will lie is output peg, the third peg is the other peg)

#include <stdio.h>
#include <stdlib.h>

int get_positive_number(const char *prompt)
{
int d;
fputs(prompt, stdout);
fflush(stdout);
if(scanf("%d", &d) == 1 && d > 0)
return d;
fputs("Invalid input: needed a positive integer\n", stderr);
exit(1);
}

void hanoi(int n, int x, int y, int z)
{
if(n) {
hanoi(n - 1, x, z, y);
printf("Move disk from peg %d to peg %d\n", x, y);
hanoi(n - 1, z, y, x);
}
}

int main(void)
{
int x, y, z, n;
x = get_positive_number("Enter input peg: ");
y = get_positive_number("Enter output peg: ");
z = get_positive_number("Enter other peg: ");
n = get_positive_number("Enter the number of disks: ");
hanoi(n, x, y, z);
return 0;
}