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

let objects: [Int] = Array(1..<11)
let split = objects.reduce(([Int](), [Int]())) { (value, object) -> ([Int], [Int]) in

    var value = value

    if object % 2 == 0 {
        value.1.append(object)
    } else {
        value.0.append(object)
    }

    return value
}

Swift 4 Solution

partition(by:)

It reorders the origin array and returns start index of subarray satisfies the predicate.

In this example it returns 7.

0..<7 elemets aren't divisible by 3 and 7..n-1 elements are divisible by 3.

 var numbers = [1,2,3,4,5,6,7,8,9,10]
 let partition = numbers.partition(by: { $0 % 3 == 0 })
 let divisibleBy3 = Array(numbers[..<partition]) //[3,6,9]
 let theRest = Array(numbers[partition...]) //[1,2,4,5,7,8,10]

// swap and return pivot
extension Array
{
    // return pivot
    mutating func swapIf(predicate: (Element) -> Bool) -> Int
    {
        var pivot = 0
        for i in 0..<self.count
        {
            if predicate( self[i] )
            {
                if i > 0
                {
                    swap(&self[i], &self[pivot])
                }

                pivot += 1
            }
        }

        return pivot
    }
}

This is my code and the concept is.. reduce memory usage.

I checked that 'swapIf' is 4-times faster than 'removeIf'.

Tags:

Arrays

Swift