I was presented this problem where I need to find matching numbers in a given array (socks) and print out how many socks found inside that array. Here is my code:
let numberOfSocks = 9
let socksArray = [10, 20, 20, 10, 10, 30, 50, 10]
func findSocks(numberOfSocks: Int, array: [Int]) {
var arr = array
var uniqueSocks = Array(Set(array))
var matchedPairs = 0
var sockCounter = 0
for i in 0..<uniqueSocks.count { // After the search, remove the element at index
sockCounter = 0
for j in 0..<arr.count {
if uniqueSocks[i] == arr[j] {
sockCounter += 1
if sockCounter % 2 == 0 {
matchedPairs += 1
sockCounter = 0
}
}
}
}
print(matchedPairs)
}
findSocks(numberOfSocks: numberOfSocks, array: socksArray)
Firstly, I have removed all the duplicates in the array so it gives me a list unique socks that I need to search for. However, I wanted to optimize this algorithm by remove the sock that I have already searched for, I have tried arr.remove(at:)
but It gave me an out of bound, I have a feeling that arr.count
is not updated correctly. Any help is welcome, thanks!