0

My case is create multiple choice questions, and i want to compare array in the same index

Correct answer:

[3, 2, 0, 2, 2]

User answer:

[3, 2, 3, 1, 1]

The expected output:

[3,2]

And this is the code

let filteredArray = correctAnswer.filter{ userAnswer.contains($0) }
print(filteredArray)

But the output:

[3, 2, 2, 2]

Thank you.

3
  • 5
    Wouldn't it be more useful to determine the indices of the correct answers? Commented Aug 27, 2018 at 11:42
  • Yea i was gonna ask what would be expected output for [3,2,0,2,2] and [3,2,3,1,2] Commented Aug 27, 2018 at 11:43
  • 1
    Strongly related: Swift 3 comparing array indexes Commented Aug 27, 2018 at 12:05

2 Answers 2

3

If you want to compare two array index by index then you can use compactMap with zip.

let correctAns = [3, 2, 0, 2, 2]
let userAns = [3, 2, 3, 1, 1]
let finalAns = zip(correctAns, userAns).compactMap({ $0 == $1 ? $0 : nil })
print(finalAns) // [3, 2]

Edit: You can even simplified this by using @MartinR suggestion.

let finalAns = zip(correctAns, userAns).filter(==).map { $1 }

If you want index of correct answer than you can get like this.

let finalAnsIndex = zip(correctAns, userAns).enumerated().compactMap({ $0.element.0 == $0.element.1 ? $0.offset : nil })
print(finalAnsIndex) // [0, 1]
Sign up to request clarification or add additional context in comments.

5 Comments

Beat me by seconds let matches = zip(correct,user).filter({$0 == $1 }).map{$1}
Or .filter(==).map { $1 }
@MartinR Great suggestion
better to use the tuple names whenever possible to improve readability compactMap{$0.element.0 == $0.element.1 ? $0.offset : nil}
@LeoDabus Thanks for the suggestion, Edited answer with it.
2

You can zip the two arrays to filter the answers that was correct:

zip(userGuesses, correctAnswers).filter { (guess, answer) in guess == answer }

Further, if you want only the right answers you can map the zipped sequence to get only the users answers:

zip(userGuesses, correctAnswers)
    .filter { (guess, answer) in guess == answer }
    .map { (guess, _) in guess }

That said, this doesn't say which questions was answered correctly. For example: If the correct answers were [1,2,3,2,1,3] and the user answered [1,3,1,2,3,3] it wouldn't be possible to know which questions the user got right (since both #1, #3, #1, #6, and #5, #6, all result in [1,3]

2 Comments

Yes, but the two values are the same so it's easy to ignore either.
Yes you are right, I have just specified the return type of your solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.