Hanoi.java 1007 B

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