Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare 2 arrays and list the differences - Swift

Tags:

I was wondering how one would go about comparing 2 boolean arrays and listing the non matching booleans.

I have written up a simple example of 2 arrays.

let array1 = [true, false, true, false]
let array2 = [true, true, true, true]

How would I compare array1 & array2 and display the non matching. I am trying to do this to check user results for a quiz game.

Thanks!

like image 384
simlimsd3 Avatar asked Jun 06 '15 16:06

simlimsd3


People also ask

Which method is used to compare two arrays in Swift?

How do I compare two arrays in Swift? To check if two arrays are equal in Swift, use Equal To == operator. Equal To operator returns a Boolean value indicating whether two arrays contain the same elements in the same order. If two arrays are equal, then the operator returns true , or else it returns false .

How do I compare two arrays of arrays?

Using Arrays. equals(array1, array2) methods − This method iterates over each value of an array and compare using equals method. Using Arrays. deepEquals(array1, array2) methods − This method iterates over each value of an array and deep compare using any overridden equals method.

How do you compare two arrays the same?

The Arrays. equals() method checks the equality of the two arrays in terms of size, data, and order of elements. This method will accept the two arrays which need to be compared, and it returns the boolean result true if both the arrays are equal and false if the arrays are not equal.


1 Answers

Here's one implementation, but whether it is the one you are after is completely impossible to say, because you have not specified what you think the answer should be:

let answer = zip(array1, array2).map {$0.0 == $0.1}

That gives you a list of Bool values, true if the answer matches the right answer, false if it does not.

But let's say what you wanted was a list of the indexes of those answers that are correct. Then you could say:

let answer = zip(array1, array2).enumerated().filter() {
    $1.0 == $1.1
}.map{$0.0}

If you want a list of the indexes of those answers that are not correct, just change == to !=.

like image 87
matt Avatar answered Sep 30 '22 04:09

matt