Home / IOS Development / Moves the elements of the array effectively in front: iOSProgramming

Moves the elements of the array effectively in front: iOSProgramming



So I have been searching for a better solution for moving elements in the matrix forward instead of deleting and than inserting on index 0. And this is what I have learned.

After watching this https://developer.apple.com/videos/play/wwdc2018/223/ fantastic talk and some research at https://github.com/apple/swift/blob/main/test/Prototypes/ Algorithms .swift I have come up with this solution:

extension MutableCollection {
  /// - Complexity: O(n log n)
  public mutating func bringFront(elementsSatisfying predicate: (Element) -> Bool) {
    self.stablePartition(count: self.count, isSuffixElement: { !predicate($0) })
  }
}

This leads to this result:

var array = [1, 2, 3, 1, 4, 5, 1, 6, 7]
array.bringFront { $0 == 1 } // [1, 1, 1, 2, 3, 4, 5, 6, 7]

So you get almost linear complexity for free 🥳

To create code above compilation you need to add some methods you can find here https://gist.github.com/japanese-goblinn/89342b2499b30252c9777fc40918ec0e

I was surprised when the next day the team quickly released https://github.com/apple/swift-algorithms which contained an updated version of stablePartition algorithm. Now you can easily implement it bringFront without copy code.


Source link