In Swift, an efficient function that separates an array into 2 arrays based on a predicate

后端 未结 7 1071
太阳男子
太阳男子 2020-12-15 04:40

Note: I\'m currently still using Swift 2.2, but open to Swift 3 solutions as well

I\'m looking to create a function that operates very closely to filter

7条回答
  •  醉梦人生
    2020-12-15 04:56

    There is a new Swift Algorithms open-source for sequence and collection algorithms, along with their related types.

    You can use the stable partition from there

    Methods for performing a stable partition on mutable collections, and for finding the partitioning index in an already partitioned collection.

    The standard library’s existing partition(by:) method, which re-orders the elements in a collection into two partitions based on a given predicate, doesn’t guarantee stability for either partition. That is, the order of the elements in each partition doesn’t necessarily match their relative order in the original collection. These new methods expand on the existing partition(by:) by providing stability for one or both partitions.

    // existing partition(by:) - unstable ordering
    var numbers = [10, 20, 30, 40, 50, 60, 70, 80]
    let p1 = numbers.partition(by: { $0.isMultiple(of: 20) })
    // p1 == 4
    // numbers == [10, 70, 30, 50, 40, 60, 20, 80]
    
    // new stablePartition(by:) - keeps the relative order of both partitions
    numbers = [10, 20, 30, 40, 50, 60, 70, 80]
    let p2 = numbers.stablePartition(by: { $0.isMultiple(of: 20) })
    // p2 == 4
    // numbers == [10, 30, 50, 70, 20, 40, 60, 80]
    

    Since partitioning is frequently used in divide-and-conquer algorithms, we also include a variant that accepts a range parameter to avoid copying when mutating slices, as well as a range-based variant of the existing standard library partition.

    The partitioningIndex(where:) method returns the index of the start of the second partition when called on an already partitioned collection.

    let numbers = [10, 30, 50, 70, 20, 40, 60]
    let p = numbers.partitioningIndex(where: { $0.isMultiple(of: 20) })
    // numbers[..

提交回复
热议问题