Swift Fun Algorithms #4: Most Common Name in Array

preview_player
Показать описание
Today, we continue with our series by going over how to get the most common name inside of an array. The main takeaway for today's lesson is to learn how to properly keep track of a running count using a Swift Dictionary object.

Complete source code here:

Рекомендации по теме
Комментарии
Автор

Man you are awesome. please keep doing this our generation really going to give you lot of blessings..iOS Swift pro..

mohammadumarkhan
Автор

Thanks Brian for always making helpful videos.

func mostCommonName() {
var hash = [String:Int]()

for name in commonNames {
hash[name] = (hash[name] ?? 0) + 1
}

var name = "", count = 0
for pair in hash {
if pair.value > count {
name = pair.key
count = pair.value
}
}
print(name, count)//Patrick, 3
}
//var commonNames = ["Saun", "Saun", "Justin", "Patrick", "Patrick", "Patrick"]
//mostCommonName()

piyushsharma
Автор

Thank you for the algorithm series! It's so helpful and enjoyable. Can you do more of these please?

leqilong
Автор

In swift 4 we can use Dictionary grouping like this
let names = ["Emma", "Olivia", "Noah", "Liam", "Ava", "Sophia",
"Emma", "Olivia", "James", "Liam", "Benjamin", "Jacob", "Emma"]
let result = Dictionary(grouping: names) { $0 }.mapValues { $0.count }
Result
["Benjamin": 1, "Emma": 3, "Ava": 1, "Olivia": 2, "Sophia": 1, "Liam": 2, "Jacob": 1, "Noah": 1, "James": 1]

RajeshKumar-mhrn
Автор

In Swift 4 you can delete code (refactor) in the first for loop by using the default value for Dictionary:
 func mostCommonNameInArray(array: [String]) -> String {
    var nameCountDictionary = [String: Int]()
   for name in array {
      nameCountDictionary[name, default: 0]  += 1 // bump existing count or add to default of zero
   }
...

johnrm
Автор

enjoy listening to these while working...

to get the max name I ended up doing the following:

let result = nameCountDictionary.max{a, b in a.value < b.value}
if let name = result!.key as? String {
return name
}

denniswhite
Автор

Ive been following the playlist for this algorithms and pausing the video and working out the answer myself for some extra practice. 

For this problem I had the same first loop, but then used nameCountDictionary.sorted() to sort by the "count" then

After some practice it actually gets fun solving these problems :P.

rufusprogrammer
Автор

Thanks for the algorithm snacks. Helpful as always!

thinkoreans
Автор

Great tutorial,
But what if there are two "most common" names, like ["a", "a", "b", "b", "c"].
Both "a" and "b" have the same count 2, so which one should the function return?
I think the function should return a sorted nameCountDictionary instead of a String.
If you input ["a", "a", "b", "b", "c"] the return value should be ["a":2, "b":"2", "c":1].

dhlsnow
Автор

Awesome tutorial, as always!

But I'm having trouble unwrapping. I get an error that says I have an optional of int type, but my code looks just like in the tutorial. . . Is there some other variable I should be unwrapping?

RutzMac
Автор

there is a solution with just one loop, , complexity O(n)

func freq(array:[String]) -> String{
var mostFreq=array[0]
var max = 1
var Dictionary = [String:Int]()
for n in array{
if let count = Dictionary[n]{
Dictionary[n] = count + 1
if(max <= count){
mostFreq=n
max = count
}
}else {
Dictionary[n]=1
}

}
return mostFreq
}

var names = ["Taha", "Roaa", "Taha", "Nor", "Nor", "Taha"]

print(freq(array:names))

tahamostafagoda
Автор

If you have the same amount of common names in an array, for example, two repeated Teds and two Bobs, then your algorithms will only return one common name Ted or Bob depending who appearing first.

wonton
Автор

+Lets Build That App Keep up the great work. Other ideas for tutorials that I think many people would find useful are:

-Swipe feature aka tinder / okcupid etc.

davidgoldberg
Автор

how come you dont need to force unwrap line 24?
if count >
should it be?
if count ! > !

mrbam
Автор

I think it would be better to initially set mostCommonName = nil, because otherwise you might've a problem with this algorithm if the most common name is an empty String ;)

miallo
Автор

Hello i have a question about array
var array = ["one", "two", "ten" ]
How to ALWAYS add item to array before "ten"

-nz
Автор

The function should return an optional string because the array could have 0 length. Here is my attempt:
func mostCommonName(in array: [String]) -> String? {
var topName: String?
var nameRecords = [String?: Int]()

for name in array {
nameRecords[name, default: 0] += 1

let newRecord = nameRecords[name]!
let topRecord = nameRecords[topName, default: 0]

if newRecord > topRecord {
topName = name
}
}

return topName
}

PythonPlusPlus
Автор

to take care of multiple names occurring most times and reduce number of lines by using a NSCountedSet,

var namesCountedSet = NSCountedSet()
var countDictionary = [Int : String]()
var maxOccurence = 0
var namesArray = ["Brian", "Neelesh", "Taylor", "Neelesh", "Brian", "Margaery", "Taylor" , "Neelesh", "Brian", "Gabriela", "", "Margaery"]
//
for name in namesArray {
if name != "" {
namesCountedSet.add(name)
}
}
//
for name in namesCountedSet {
let count = namesCountedSet.count(for: name)
maxOccurence = count > maxOccurence ? count : maxOccurence
countDictionary[count] = countDictionary[count] == nil ? name as! String : "\(countDictionary[count]!), \(name as! String)"
}
//
if let mostOccured = countDictionary[maxOccurence] {
print(mostOccured)
}

neeleshshah
Автор

Thanks so much for this video series! I hope that you would continue to do more these.

ArjunKodur
Автор

Or this could be done in the latest version ;)

var nameFrequency: [String: Int] = [:]

for name in arr {
nameFrequency[name, default: 0] += 1
}

let mostCommon = nameFrequency.max { a, b in a.value < b.value }

return mostCommon?.key

swayamrustagi