How to do array.intersects(otherArray)?

Hi all,

Is there an easy way to find out if one array has elements in common with another array? Something like this:

let modifiers = ["26", "25", "GY", "GN"]
let special = ["GA", "GY"]

modifiers.intersects(special) // Returns true because "GY" exists in both arrays

Is there anything in the standard Swift library to do this? I wrote a quick/dirty extension to accomplish the above as follows:

extension Array 
    where Element: Equatable
{
    func intersects(_ other: Array) -> Bool 
    {
        for e in other {
            if contains(where: {$0 == e}) {
                return true
            }
        }
        return false
    }
}

I’m on mobile, so I can’t give code examples, but a quick comment: you should sort your arrays and then go through them linearly in parallel, keeping them “about equal” by incrementing the index of whichever array “falls behind”. That will reduce the complexity of your solution to O(n log n) rather than O(n2).

If the elements are Hashable you could make a Set from one and intersect it with the other.

2 Likes

Right, the lack of an efficient algorithm for all Arrays with Equatable elements is why this isn't there. You can do it with a Set if the elements are Hashable and by sorting copies if all elements are Comparable, but otherwise you're stuck with something inefficient, and even those two strategies require extra time and space.