15,671,318 members
1.00/5 (1 vote)
See more:
move disks from source(s) to destination(d) using helper(h)

1
2
3
__ __ __
S H D

rules :
1.Only one disk can be moved at a time.
2.Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack. In other words, a disk can only be moved if it is the uppermost disk on a stack.
3.No larger disk may be placed on top of a smaller disk.

output the program gives :

transfer 1 from s to d
transfer 2 from s to h
transfer 1 from d to h -> shouldn't be there
transfer 3 from s to d
transfer 1 from h to s -> should come after next line, violates rule 2 places 2 before 1
transfer 2 from h to d
transfer 1 from s to d -> shouldn't be there

What I have tried:

video tutorial shows this program which give above output which is wrong

Java
```public class towerOfhanoi {
public void toh(int n, String src, String helper, String destination) {
if (n == 0) {
return;
}
toh(n - 1, src, destination, helper);
System.out.println("transfer " + n + " from" + src + " to" + destination);
toh(n - 1, helper, src, destination);

}
public static void main(String[] args){
int n=3;
towerOfhanoi th = new towerOfhanoi();
th.toh(n,"s","h","d");
}
}```

can some one code for this output:

1 from s to d
2 from s to h
1 from d to h
3 from s to d
1 from h to s
2 from h to d
1 from s to d
Posted
Updated 7-Jan-23 5:28am
v2
Richard MacCutchan 7-Jan-23 11:14am
How about you do it yourself? There are only seven simple steps.
Shivam Siddharth 7-Jan-23 11:24am
using recursion for eg step 2 in which value is 2 will also recurse for value 1 also which i don't want to happen and if i put a 'if' condition to stop that from happening step 3 won't be executed
how should i get the desired output