Skip to content

Instantly share code, notes, and snippets.

@BirgitPohl
Last active January 6, 2016 18:58
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 BirgitPohl/3095a3f5daa7de94634b to your computer and use it in GitHub Desktop.
Save BirgitPohl/3095a3f5daa7de94634b to your computer and use it in GitHub Desktop.
Goal is to write a hanoi tower program where discs can not jump from position A to C, they need to move to position B first in order to get to position C. It is a recursive solution. I took a look at the Sierpiński triangle on Wikipedia and figured out how it could work. https://en.wikipedia.org/wiki/Tower_of_Hanoi
public class Hanoi {
//Goal is to write a program where discs can not jump from position A to C, they need to move to position B in order to get to position C.
static void move (
int n, // Number of discs 'n'
char start, // start position
char help, // helping position (place in the middle)
char destination) { // destination position
if (n == 1) {
System.out.println("Disc " + n + " from " + start + " to " + help);
System.out.println("Disc " + n + " from " + help + " to " + destination);
}
else {
move(n - 1, start, help, destination);
System.out.println("Disc " + n + " from " + start + " to " + help);
move(n - 1, destination, help, start);
System.out.println("Disc " + n + " from " + help + " to " + destination);
move(n - 1, start, help, destination);
}
}
public static void main (String argv[]) {
int n;
System.out.print("Number of Discs: ");
n = Keyboard.readInt(); // You need this, which is not written by me, so I won't share it. U can simply program something else or work with arguments in the console.
if (n > 0) {
System.out.println("Disc movement: ");
move(n, 'A', 'B', 'C');
}
else
System.out.println("Number is not positive.");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment