Home > database >  Swift - I need to find elements from array 2 that are not in array 1
Swift - I need to find elements from array 2 that are not in array 1

Time:03-18

If an element occurs multiple times in the lists, you must ensure that the frequency of that element in both lists is the same. If that is not the case, then it is also a missing element. Only include a missing element once, even if it is missing multiple times.

for example : its should work like that:

let array1 = [8, 8, 7, 2, 1, 7, 9]
let array2 = [14, 8, 2, 7, 7]

solve(array1, array2) 

I have two arrays, array1 and array2, I need to show 14 and 8 from array2 in the answer, because there is no 14 in array1 and 8 is repeated twice (in array1 ) and in array2 the digit 8 is only once

// Answer: [8, 14]

it should also work with string, double,float But I have no idea how to do it

i tried something like this, but it doesn't fit

let array1 = [8, 8, 7, 2, 1, 7, 9]
let array2 = [14, 8, 2, 7, 7]


for (index, item) in array2.enumerated() where array1.contains(item {
    print(array2[index])
}

CodePudding user response:

Loop through array2 and check each value against array1. If a number doesn’t exist or exists with a different count then add it to the result collection. To only keep unique numbers for the result we use a set

var result = Set<Int>()

array2.forEach { number in
    if array1.contains(number) {
        if array1.filter { $0 == number }.count != array2.filter { $0 == number }.count {
            result.insert(number)
        }
    } else {
        result.insert(number)
    }
}

CodePudding user response:

You can get the collection elements frequency and just filter the elements that doesnt match from second collection

let array1 = [8, 8, 7, 2, 1, 7, 9]
let array2 = [14, 8, 2, 7, 7]
let frequency1 = array1.reduce(into: [:]) { $0[$1, default: 0]  = 1 }
let frequency2 = array2.reduce(into: [:]) { $0[$1, default: 0]  = 1 }
let elements = array2.filter { frequency1[$0] != frequency2[$0] }
elements  //  [14, 8]
  • Related