Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

See if 2 arrays contain same element (swift 2.0)

Tags:

arrays

swift

I have 2 arrays of strings. For example, let's say this:

 let array1 = ["string1", "string2", "string3", "string4", "string5"]
 let array2 = ["string8", "string4", "string3", "string367", "string5"]

I want to compare and see if the 2 arrays contain any of the same elements, and then place the result into an array of bools. Like say "the first element in array1 is "string1", now let's go through and see if any element in array2 is the same as "string1", if they are, the first element in the boolArray will be true, if not, it will be false." The result of doing this for comparing array1 to array2 here would yield a boolArray of

  var boolArray = [false, false, true, true, true]

How can I do this? I tried this:

for y in array1 {
        for z in array2 {
            if y == z {
                self.boolArray.append(true)
            }
            else {
                self.boolArray.append(false)
            }
        }
    }

but it didn't work, as the boolArray contained 25 elements, and it should only contain 5. Maybe there is some swift function that I am not aware of that does a lot of this for us?

like image 800
jjjjjjjj Avatar asked Nov 02 '15 19:11

jjjjjjjj


2 Answers

Try this:

for y in array1 {
        self.boolValue = false
        for z in array2 {
            if y == z {
                    self.boolValue = true
            }
        }
        self.boolArray.append(self.boolValue)
    }

Using your existing code as a baseline, you only want to write to the boolean array AFTER you finish iterating through your comparator array (Array 2). This is a very iterative approach but should work.

like image 104
Dan Avatar answered Sep 28 '22 03:09

Dan


If you are content that any element in either array should match any element in the other array, then the algorithm is simple: convert both arrays to sets and take the intersection of the two sets. The resulting set will be all the elements present in both arrays.

let array1 = ["string1", "string2", "string3", "string4", "string5"]
let array2 = ["string8", "string4", "string3", "string367", "string5"]
let result = Set(array1).intersect(Set(array2))

Observe, however, that this merely answers the question about the presence of elements; it gives up the notion of order.

like image 41
matt Avatar answered Sep 28 '22 03:09

matt