Created
May 10, 2012 15:49
-
-
Save baisong/2654051 to your computer and use it in GitHub Desktop.
Implements Towers of Hanoi in Dart
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
/** | |
* Implements Towers of Hanoi Game | |
* @see http://en.wikipedia.org/wiki/Towers_of_hanoi | |
*/ | |
main() { | |
// Formats a move to output. | |
String say(String from, String to) => "move $from -> $to"; | |
// Makes a move and recursively triggers next moves, if any. | |
hanoi(int discs, String a, String b, String c) { | |
// Makes a move only if there are discs. | |
if (discs > 0) { | |
// Announces this move, from A to C. | |
print(say(a, c)); | |
// Triggers the next step: from A to B. | |
hanoi(discs - 1, a, c, b); | |
// Triggers the last step: from B to C. | |
hanoi(discs - 1, b, a, c); | |
} | |
} | |
// Demonstrates a game with 3 discs on pegs labelled '1', '2' and '3'. | |
hanoi(3, '1', '2', '3'); | |
} | |
/** | |
* Outputs: | |
* move 1 -> 3 | |
* move 1 -> 2 | |
* move 3 -> 2 | |
* move 1 -> 3 | |
* move 2 -> 1 | |
* move 2 -> 3 | |
* move 1 -> 3 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment