Guest User

Untitled

a guest
Jul 23rd, 2018
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.97 KB | None | 0 0
  1. /// Reorder elements in-place into the next permutation, returning false when
  2. /// the collection has been permuted into lexicographical order. To cycle
  3. /// through all permutations, start with a lexicographically-sorted collection
  4. /// and permute until it returns false.
  5. extension MutableCollection where Self: BidirectionalCollection {
  6. mutating func permute(
  7. by areInIncreasingOrder: (Element,Element)->Bool
  8. ) -> Bool {
  9. guard !isEmpty else { return false }
  10. var i = index(before: endIndex)
  11.  
  12. while i != startIndex {
  13. let j = i
  14. formIndex(before: &i)
  15. let x = self[i]
  16. if areInIncreasingOrder(x, self[j]) {
  17. guard let k = lastIndex(where: { areInIncreasingOrder(x, $0)})
  18. else { preconditionFailure("Nodetermistic comparison behavior")}
  19. swapAt(i, k)
  20. self[j...].reverse()
  21. return true
  22. }
  23. }
  24. reverse()
  25. return false
  26. }
  27. }
  28.  
  29. var a = Array((1...4).reversed())
  30. repeat {
  31. print(a)
  32. } while a.permute(by: >)
Add Comment
Please, Sign In to add comment