Skip to content

Instantly share code, notes, and snippets.

@ericdke
Created January 24, 2016 00:35
Show Gist options
  • Select an option

  • Save ericdke/acb14bf91d138b72ac95 to your computer and use it in GitHub Desktop.

Select an option

Save ericdke/acb14bf91d138b72ac95 to your computer and use it in GitHub Desktop.
Swift: Heap's algorithm with Generics
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