Created
December 10, 2018 00:49
-
-
Save nanoxd/9a7e07746dce4ec3d852370b8c9c3bee to your computer and use it in GitHub Desktop.
[PermutationIterator] Use of Heap's Algorithm to create permutations
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 struct PermutationIterator<T>: IteratorProtocol { | |
private var hasReturnedInitial = false | |
private var a: [T] | |
private var c: [Int] | |
private let n: Int | |
private var i = 0 | |
public init<C: Collection>(_ values: C) where C.Element == T { | |
a = Array(values) | |
n = a.count | |
c = Array(repeating: 0, count: n) | |
} | |
public mutating func next() -> [T]? { | |
if hasReturnedInitial == false { | |
hasReturnedInitial = true | |
return a | |
} | |
// this uses a non-recursive version of Heap's Algorithm | |
// https://en.wikipedia.org/wiki/Heap%27s_algorithm | |
while i < n { | |
if c[i] < i { | |
if i % 2 == 0 { | |
a.swapAt(0, i) | |
} else { | |
a.swapAt(c[i], i) | |
} | |
c[i] += 1 | |
i = 0 | |
return a | |
} else { | |
c[i] = 0 | |
i += 1 | |
} | |
} | |
return nil | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment