Created
September 20, 2017 00:57
-
-
Save scottrhoyt/2f393b5224056b45e2cb8afcdeb63c64 to your computer and use it in GitHub Desktop.
Heap's Algorithm for permutations in Swift
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
// 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