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

W

wahid

• 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
 
A

Antoninus Twink

• 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;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,997
Messages
2,570,240
Members
46,830
Latest member
HeleneMull

Latest Threads

Top