Last active
September 18, 2017 03:53
-
-
Save yossan/bf1b83418334319fd0a5c2fd0c72c3ef to your computer and use it in GitHub Desktop.
Hanoi Tower
This file contains hidden or 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
| /* | |
| Hanoi Tower | |
| Calucuating How many moves in Swift | |
| result is 2^n - 1 | |
| */ | |
| func hanoi(_ n: Int, from: String="from", target: String="target", other: String="other") -> Int { | |
| guard n != 0 else { return 0 } | |
| // move top of n-1 disks on from to other | |
| var count = hanoi(n-1, from: from, target: other, other: target) | |
| // move the last disk to target | |
| count += 1 | |
| // move n-1 disks on other to target | |
| count += hanoi(n-1, from: other, target: target, other: from) | |
| return count | |
| } | |
| print(hanoi(3)) // 7 | |
| print(hanoi(4)) // 15 | |
| print(hanoi(5)) // 31 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment