Created
January 24, 2016 00:35
-
-
Save ericdke/acb14bf91d138b72ac95 to your computer and use it in GitHub Desktop.
Swift: Heap's algorithm with Generics
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
| public extension CollectionType { | |
| var permutations: [[Generator.Element]] { | |
| func permute<C: CollectionType>(items: C) -> [[C.Generator.Element]] { | |
| var scratch = Array(items) // This is a scratch space for Heap's algorithm | |
| var result: [[C.Generator.Element]] = [] // This will accumulate our result | |
| // Heap's algorithm | |
| func heap(n: Int) { | |
| if n == 1 { | |
| result.append(scratch) | |
| return | |
| } | |
| for i in 0..<n-1 { | |
| heap(n-1) | |
| let j = (n%2 == 1) ? 0 : i | |
| swap(&scratch[j], &scratch[n-1]) | |
| } | |
| heap(n-1) | |
| } | |
| // Let's get started | |
| heap(scratch.count) | |
| // And return the result we built up | |
| return result | |
| } | |
| // Return all permutations | |
| return permute(self) | |
| } | |
| } | |
| public extension String { | |
| var permutations: [String] { | |
| return self.characters.permutations.map { String($0) } | |
| } | |
| } | |
| print([1,2,3,4].permutations) | |
| print("ERIC".permutations) | |
| print("ERIC".characters.permutations) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment