Collection.swift 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. //
  2. // Collection.swift
  3. // LoopKit
  4. //
  5. // Created by Michael Pangburn on 2/14/19.
  6. // Copyright © 2019 LoopKit Authors. All rights reserved.
  7. //
  8. /// Returns the cartesian product of a sequence and a collection.
  9. ///
  10. /// O(1), but O(_n_*_m_) on iteration.
  11. /// - Note: Don't mind the scary return type; it's just a lazy sequence.
  12. func product<S: Sequence, C: Collection>(_ s: S, _ c: C) -> LazySequence<FlattenSequence<LazyMapSequence<S, LazyMapSequence<C, (S.Element, C.Element)>>>> {
  13. return s.lazy.flatMap { first in
  14. c.lazy.map { second in
  15. (first, second)
  16. }
  17. }
  18. }
  19. extension Collection {
  20. /// Returns a sequence containing adjacent pairs of elements in the ordered collection.
  21. func adjacentPairs() -> Zip2Sequence<Self, SubSequence> {
  22. return zip(self, dropFirst())
  23. }
  24. }
  25. extension RandomAccessCollection {
  26. /// Returns all unique pair combinations of elements in the collection.
  27. ///
  28. /// O(1), but O(*n*²) on iteration.
  29. /// - Note: Don't mind the scary return type; it's just a lazy sequence.
  30. func allPairs() -> LazyMapSequence<LazyFilterSequence<FlattenSequence<LazyMapSequence<Indices, LazyMapSequence<Indices, (Index, Index)>>>>, (Element, Element)> {
  31. return product(indices, indices).filter(<).map {
  32. (self[$0], self[$1])
  33. }
  34. }
  35. }
  36. extension RangeReplaceableCollection where Index: Hashable {
  37. /// Removes the elements at all of the given indices.
  38. ///
  39. /// O(_n_*_m_)
  40. mutating func removeAll<S: Sequence>(at indices: S) where S.Element == Index {
  41. let arranged = Set(indices).sorted(by: >)
  42. for index in arranged {
  43. remove(at: index)
  44. }
  45. }
  46. }