Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - Find duplicates Elements in a List

Tags:

ios

swift

i have the following list of UITextField:

let list = [(name1TextField, phone1TextField), (name2TextField, phone2TextField), (name3TextField, phone3TextField), (name4TextField, phone4TextField), (name5TextField, phone5TextField)]

i'm trying to find phones duplicates and print them out

EDIT

e.g. (tuples could be empty)

list = [("john", "555-444-333"), ("james", "555-444-333"), ("",""), ("bob", "333-222-111"), ("nancy", "222-111-444"), ]

output 555-444-333

how can i do?

like image 386
Mono.WTF Avatar asked Sep 26 '22 09:09

Mono.WTF


2 Answers

Given this

var name1TextField: UITextField!
var phone1TextField: UITextField!
var name2TextField: UITextField!
var phone2TextField: UITextField!
var name3TextField: UITextField!
var phone3TextField: UITextField!
var name4TextField: UITextField!
var phone4TextField: UITextField!
var name5TextField: UITextField!
var phone5TextField: UITextField!

And this

let list = [(name1TextField, phone1TextField), (name2TextField, phone2TextField), (name3TextField, phone3TextField), (name4TextField, phone4TextField), (name5TextField, phone5TextField)]

Solution

let repeatedPhones = list
    .flatMap { $0.1?.text }
    .reduce([String:Int]()) { (var dict, phone) -> [String:Int] in
        dict[phone] = (dict[phone] ?? 0) + 1
        return dict
    }
    .filter { $0.1 > 1 && !$0.0.isEmpty }
    .map { $0.0 }
like image 128
Luca Angeletti Avatar answered Oct 11 '22 17:10

Luca Angeletti


Using dictionary to record how many time you see a phone number:

var dict = [String: Int]()

And then go thru the whole list:

for (_, phone) in list {

    if let count = dict[phone] {
        dict[phone] = count + 1
    } else {
        dict[phone] = 1
    }
}

After this you will have a dictionary which contains the phone number and the count of each phone number appear in the list

for item in dict {
    if item.1 > 1 {
        print(item.0)
    }
}

This method has a time complexity: O(2n)

And this question looks like a duplicate of Find Duplicate Elements In Array Using Swift

like image 1
Breek Avatar answered Oct 11 '22 19:10

Breek