Last active
October 6, 2018 23:49
-
-
Save MaciejGad/543c0765fdda75cb22de to your computer and use it in GitHub Desktop.
Simple implementation of hanoi algorithm. If you want more information about this algorithm watch this video https://www.youtube.com/watch?v=3YH0SZYAzOQ
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
enum Tower:String { | |
case A | |
case B | |
case C | |
} | |
func hanoi(_ disk: Int, from: Tower, using: Tower, | |
to: Tower, output: inout [String]) { | |
if disk == 1 { | |
output.append("\(from.rawValue)->\(to.rawValue)") | |
return | |
} | |
hanoi(disk - 1, from: from, using: to, to: using, | |
output: &output) | |
hanoi(1, from: from, using: using, to: to, | |
output: &output) | |
hanoi(disk - 1, from: using, using: from, to: to, | |
output: &output) | |
} | |
var result:[String] = [] | |
hanoi(3, from: .A, using: .B, to: .C, output: &result) | |
let out = result.joined(separator:", ") | |
print(out) | |
//A->C, A->B, C->B, A->C, B->A, B->C, A->C |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment