-3

I make app for performing tests. For check for valid answer i have array of correct answers, of type [Int]. It may be, for example, [1, 5, 10].

Also i have array of questions id's that user entered, also [Int] type.

Now i have to somehow compare that arrays. But, [1,5,10] should be equal to [10,1,5] and [5,1,10], etc., because order is not guaranteed. How to achieve that?

Evgeniy Kleban
  • 6,794
  • 13
  • 54
  • 107
  • what happens when there are duplicates? –  Aug 29 '17 at 15:41
  • 1
    And if your need to deal with duplicate values in the array then https://stackoverflow.com/questions/40883818/check-if-elements-in-two-arrays-are-same-irrespective-of-index is a better duplicate. – rmaddy Aug 29 '17 at 15:45

2 Answers2

1

If you want a function that returns true if an array contains all elements of your array and only those elements, you can use below Array Extension. If the length of the two arrays isn't the same or if one of the elements in your array isn't present in the other array, the function returns false, otherwise it returns true.

let array1 = [1,5,10]
let array2 = [5,10,1]
let array3 = [10,1,5]
let otherArray = [2,1,5,10]
let anotherArray = [2,3,5]

extension Array where Element == Int {
    func isUnorderedEqual(to array: [Element])->Bool{
        if self.count == array.count {
            for element in self {
                if array.index(of: element) == nil {
                    return false
                }
            }
            return true
        } else {
            return false
        }
    }
}

print(array1.isUnorderedEqual(to: array2)) //true
print(array1.isUnorderedEqual(to: array3)) //true
print(array1.isUnorderedEqual(to: otherArray)) //false
print(array1.isUnorderedEqual(to: anotherArray)) //false
Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
-1

You can filter for any correct answers not in the list of answers and look if any such item exists.

let correctAnswers: [Int] = [1, 5, 10]

func validate(answers: [Int]) -> Bool {
    return answers.filter({ answer in !correctAnswers.contains(answer) }).isEmpty
}

validate(answers: [10, 1, 5])
Francis.Beauchamp
  • 1,323
  • 15
  • 28