Home > Enterprise >  Improving on the efficiency of my filtering of arrays with potentially hundreds of thousands of elem
Improving on the efficiency of my filtering of arrays with potentially hundreds of thousands of elem

Time:12-26

I have an array of numbers. I want to find those in array1 that aren't also in array2, like this:

var array1 = [1, 2, 3, 4]
var array2 = [2, 4, 5, 6]

var result = [1, 3]

I've solved the problem by looping through all the numbers in the array2 and adding them to a dictionary. Then I loop through array1 and add those that aren't in the dictionary to the result array:

var result: [Int] = []
var numbersDict: [Int : Bool] = [:]

for element in array2 {
  numbersDict[element] = true
}

for element in array1 {
  if numbersDict[element] == nil {
    result.append(element)
  }
}

I also want to find those in array2 that aren't in array1

var array1 = [1, 2, 3, 4]
var array2 = [2, 4, 5, 6]

var result = [5, 6]

I've solved this like this:

var result: [Int] = []
var numbersDict: [Int : Bool] = [:]

for element in array1 {
  numbersDict[element] = true
}

for element in array2 {
  if numbersDict[element] == nil {
    result.append(element)
  }
}

How can I do this in the most efficient way? Assuming that these arrays could potentially be tens if not hundreds of thousands of numbers long. Should I be using sorting?

CodePudding user response:

Just use Set.

Example which gets elements in array1 but not in array2:

let array1: Set = [1, 2, 3, 4]
let array2: Set = [2, 4, 5, 6]

let result = array1.subtracting(array2)
print(result)
// Prints: [1, 3]  <- Order may vary since it is a set

Just switch the two sets around to get the opposite result, of in array2 but not in array1.

There are lots of Set operations, another one is intersection(_:):

let result = array1.intersection(array2)
print(result)
// Prints: [2, 4]  <- Again, no order
  • Related