Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

📚 The CoCalc Library - books, templates and other resources

132940 views
License: OTHER
1
/**
2
This is an aotomatic Hanoi algorithm. It solves a given game.
3
*/
4
public class Hanoi {
5
6
public static void main (String[] args) {
7
Pole a = new Pole(3);
8
Pole b = new Pole(3);
9
Pole c = new Pole(3);
10
Disc d1 = new Disc(1);
11
Disc d2 = new Disc(2);
12
Disc d3 = new Disc(3);
13
14
a.push(d3);
15
a.push(d2);
16
a.push(d1);
17
18
System.out.println("from: \n" + a);
19
System.out.println("help: \n" + b);
20
System.out.println("to: \n" + c);
21
move(a, b, c);
22
System.out.println("from: \n" + a);
23
System.out.println("help: \n" + b);
24
System.out.println("to: \n" + c);
25
}
26
27
public static void move(Pole from, Pole help, Pole to) {
28
if(from == null | to == null || help == null) {
29
throw new IllegalArgumentException("Pole is null");
30
}
31
32
move(from.getSize(), from, help, to);
33
}
34
35
private static void move(int n, Pole from, Pole help, Pole to) {
36
if(n > 0) {
37
move(n - 1, from, to, help);
38
to.push(from.pop());
39
move(n - 1, help, from, to);
40
}
41
}
42
}
43