Swift - search for duplicate items in a list

I have the following list of UITextField:

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

I try to find duplicate phones and print them

EDIT

eg. (tuples may 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 this?

+5
source share
4 answers

Considering 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 one

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

Decision

 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 } 
+3
source

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

var dict = [String: Int]()

And then go through the whole list:

 for (_, phone) in list { if let count = dict[phone] { dict[phone] = count + 1 } else { dict[phone] = 1 } } 

After that, you will have a dictionary that contains the phone number, and the number of each phone number will appear in the list

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

This method has time complexity: O (2n)

And this question looks like a duplicate Find duplicate elements in an array using Swift

+1
source

You can create a list of the last elements of the tuple, and then, adding them to the new array, check if they are contained in the array. So something like:

 func processList(list) -> String { var bufferArray[String] = [] for (int i = 0; i < list.size; i++) { if !(bufferArray.contains( list[i].1 )) { bufferArray.add(list[i].1) else { return list[i].1 } } } 
0
source

I would do the following:

 var duplicates = [] var set = Set<String>() for tuple in list { if set.contains(tuple.phoneTextField.text) { duplicates.append(tuple.phoneTextField.text) } else { set.insert(tuple.phoneTextField.text) } } 

In the end, you do whatever you want with an array of duplicates .

0
source

Source: https://habr.com/ru/post/1243069/


All Articles