Skip to content

Instantly share code, notes, and snippets.

@robsonsky
Created June 24, 2019 21:51
Show Gist options
  • Save robsonsky/854a4bb6b3b3154495487e98d2e2b588 to your computer and use it in GitHub Desktop.
Save robsonsky/854a4bb6b3b3154495487e98d2e2b588 to your computer and use it in GitHub Desktop.
import Foundation
func sockMerchant(n: Int, ar: [Int]) -> Int {
//check if the amount of socks is valid
if n < 1 || n > 100 {
print("Please, enter a valid array (1 to 100 items).")
return 0
}
let result = findPairs(ar: ar, pairs: 0)
print(result)
return result
}
func findPairs(ar: [Int], pairs: Int) -> Int {
var res = pairs
if ar.count > 0 {
var newAr = ar
let sock = newAr.remove(at: 0)
for (index, element) in newAr.enumerated() {
if element == sock {
newAr.remove(at: index)
res += 1
break
}
}
return findPairs(ar: newAr, pairs: res)
}
return res
}
sockMerchant(n: 7, ar: [1,2,3,4,1,5,2])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment