fork download
  1. /** finger exercise: Lucas' "Towers of Hanoi".
  2.  * Based on code presented at https://c...content-available-to-author-only...e.com/a/116290/93149 */
  3. class Ideone {
  4.  
  5. static class LucasTower<E> extends java.util.ArrayDeque<E> {
  6. private static final long serialVersionUID = 3049952862056404246L; // YAGNI?
  7. private final String name;
  8.  
  9. public LucasTower(String name) { this.name = name; }
  10. // YAGNI LucasTower(String n, int c) { super(c); name = n; }
  11. void addEach(E ...n) { for (E e : n) { add(e); } }
  12. /** Do as see fit with {@code count, mid, to} just before
  13.   * the bottom disk of some invocation of {@code move} is moved. Old school override */
  14. public void before(int count, LucasTower<E> mid, LucasTower<E> to) {
  15. System.out.println(name + ": pushing " + peek() + " to " + to.name);
  16. }
  17. /** Do as see fit with {@code count, mid, to} just after
  18.   * the bottom disk of some invocation of {@code move} is moved. Old school override */
  19. public void after(int count, LucasTower<E> mid, LucasTower<E> to) {
  20. // System.out.println(name + ": pushed popped " + to.peek() + " to " + to.name);
  21. }
  22. /** move the top {@code count} discs to {@code to} */
  23. public void move(int count, LucasTower<E> mid, LucasTower<E> to) {
  24. if (0 < count) {
  25. move(count - 1, to, mid);
  26. before(count, mid, to);
  27. to.push(pop());
  28. after(count, mid, to);
  29. mid.move(count - 1, this, to);
  30. }
  31. }
  32. }
  33.  
  34. public static void main(String[] args) {
  35. LucasTower<Number>
  36. from= new LucasTower<>("A"),
  37. mid = new LucasTower<>("B"),
  38. to = new LucasTower<>("C");
  39. from.addEach(10, 15, 20, 25);
  40. from.move(from.size(), mid, to);
  41. }
  42. }
Success #stdin #stdout 0.11s 320576KB
stdin
Standard input is empty
stdout
A: pushing 10 to B
A: pushing 15 to C
B: pushing 10 to C
A: pushing 20 to B
C: pushing 10 to A
C: pushing 15 to B
A: pushing 10 to B
A: pushing 25 to C
B: pushing 10 to C
B: pushing 15 to A
C: pushing 10 to A
B: pushing 20 to C
A: pushing 10 to B
A: pushing 15 to C
B: pushing 10 to C