Skip to content

Instantly share code, notes, and snippets.

@nanoxd
Created December 10, 2018 00:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nanoxd/9a7e07746dce4ec3d852370b8c9c3bee to your computer and use it in GitHub Desktop.
Save nanoxd/9a7e07746dce4ec3d852370b8c9c3bee to your computer and use it in GitHub Desktop.
[PermutationIterator] Use of Heap's Algorithm to create permutations
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