Skip to content

Instantly share code, notes, and snippets.

@scottrhoyt
Created September 20, 2017 00:57
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scottrhoyt/2f393b5224056b45e2cb8afcdeb63c64 to your computer and use it in GitHub Desktop.
Save scottrhoyt/2f393b5224056b45e2cb8afcdeb63c64 to your computer and use it in GitHub Desktop.
Heap's Algorithm for permutations in Swift
// https://en.wikipedia.org/wiki/Heap%27s_algorithm
import Foundation
/**
Generates all possible permutations of `data` using Heap's Algorithm
- parameters:
- data: The data to permute
- output: A closure called with each permutation of the data
*/
func heapPermutation<T>(data: inout Array<T>, output: (Array<T>) -> Void) {
generate(n: data.count, data: &data, output: output)
}
func generate<T>(n: Int, data: inout Array<T>, output: (Array<T>) -> Void) {
if n == 1 {
output(data)
} else {
for i in 0 ..< n {
generate(n: n - 1, data: &data, output: output)
if n % 2 == 0 {
data.swapAt(i, n - 1)
} else {
data.swapAt(0, n - 1)
}
}
}
}
var data = ["a", "b", "c"] // This can be any array
heapPermutation(data: &data) { result in print(result) }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment