Skip to content

Instantly share code, notes, and snippets.

@svpino
Last active October 1, 2017 17:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save svpino/de435984bc58c64c60a4 to your computer and use it in GitHub Desktop.
Save svpino/de435984bc58c64c60a4 to your computer and use it in GitHub Desktop.
Programming challenge: towers of Hanoi
// Programming challenge: towers of Hanoi
// Original post: https://blog.svpino.com/2015/06/07/programming-challenge-towers-of-hanoi
public class Main {
private static int NUMBER_OF_DISKS = 3;
public static void towersOfHanoi(int n, String rod1, String rod2, String rod3) {
if (n == 1) {
System.out.println("* Move disk from " + rod1 + " to " + rod3);
}
else {
towersOfHanoi(n - 1, rod1, rod3, rod2);
System.out.println("* Move disk from " + rod1 + " to " + rod3);
towersOfHanoi(n - 1, rod2, rod1, rod3);
}
}
public static void main(String[] args) {
System.out.println("Number of moves: " + (int) (Math.pow(2, NUMBER_OF_DISKS) - 1));
System.out.println();
towersOfHanoi(NUMBER_OF_DISKS, "[1]", "[2]", "[3]");
}
}
@kfird214
Copy link

kfird214 commented Oct 1, 2017

wow cool solution!
How did you came up with this solution?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment