Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /// Reorder elements in-place into the next permutation, returning false when
- /// the collection has been permuted into lexicographical order. To cycle
- /// through all permutations, start with a lexicographically-sorted collection
- /// and permute until it returns false.
- extension MutableCollection where Self: BidirectionalCollection {
- mutating func permute(
- by areInIncreasingOrder: (Element,Element)->Bool
- ) -> Bool {
- guard !isEmpty else { return false }
- var i = index(before: endIndex)
- while i != startIndex {
- let j = i
- formIndex(before: &i)
- let x = self[i]
- if areInIncreasingOrder(x, self[j]) {
- guard let k = lastIndex(where: { areInIncreasingOrder(x, $0)})
- else { preconditionFailure("Nodetermistic comparison behavior")}
- swapAt(i, k)
- self[j...].reverse()
- return true
- }
- }
- reverse()
- return false
- }
- }
- var a = Array((1...4).reversed())
- repeat {
- print(a)
- } while a.permute(by: >)
Add Comment
Please, Sign In to add comment