Nathan McKaskle
Nathan McKaskle

Reputation: 3063

Intersecting more than 2 Array Sets?

I found this question answered here regarding the intersection of two arrays. What if I want to find out what's in common between more than two arrays of items? What if I don't know how many arrays there will be?

UPDATE:

Here's my code and attempt to intersect a number of unknown arrays but I can only get up to two arrays in this scenario before I have to worry about index out of range problems and losing sets in the next loop around. I thought about storing them in temporary variables as they loop through, but I'm not sure if that's the best way.

    //anyArray is an array of string arrays containing
    //the items I want to intersect

    let count = anyArray.count - 1
    //var temp: Array<String>

    for index in 0...count {
        let item1 = anyArray[index] as! Array<String>
        if index < count {
            let item2 = anyArray[index + 1] as! Array<String>
            let set1 = Set(item1)
            let set2 = Set(item2)
            let inter = set1.intersect(set2)
            print(inter)
        }
    }

UPDATE 2

The final answer was a combination of Phillip's answer below and the code I am posting here. This answers the question of "What if you don't know how many arrays there will be?"

The trick was to set and initialize a temporary Set for intersecting in the next go round in the loop. I had to initialize it or else it wouldn't let me use it.

let count = anyArray.count - 1
var inter = Set<String>()

for index in 0...count {
   if index == 0 {
       let item1 = anyArray[index] as! Array<String>
       let item2 = anyArray[index + 1] as! Array<String>
       let set1 = Set(item1)
       let set2 = Set(item2)
       inter = set1.intersect(set2)

   } else {
       if index < count {
           let item = anyArray[index + 1] as! Array<String>
           inter = inter.intersect(item)
       }
   }
}

print(inter)

Upvotes: 0

Views: 42

Answers (1)

Phillip Mills
Phillip Mills

Reputation: 31016

Try this in a playground and inspect the data type of inter:

let a1: Array = [1, 1, 2, 3, 5, 8]
let a2: Array = [1, 2, 3, 4, 5]
let a3: Array = [1, 2, 4, 8, 16]

let anyArray = [a1, a2, a3]

var inter = Set(anyArray[0])

for idx in 1 ..< anyArray.count {
    inter = inter.intersect(anyArray[idx])
}

print("\(inter)")

Upvotes: 1

Related Questions