Last active
January 6, 2016 18:58
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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