-
Notifications
You must be signed in to change notification settings - Fork 0
/
Contents.swift
39 lines (28 loc) · 962 Bytes
/
Contents.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// MARK: - FIND MOST COMMON ELEMENT IN ARRAY
var colors = ["Red", "Green", "Blue", "Red", "Red", "Blue", "Blue", "Blue"]
func mostCommonElement(inArray array: [String]) -> String? {
var result: String?
var dictionary = [String: Int]()
array.forEach { element in
if let count = dictionary[element] {
dictionary[element] = count + 1
print("If Block -> Color: \(element) Count is \(dictionary[element])")
} else {
dictionary[element] = 1
print("Else Block -> Color: \(element) Count is \(dictionary[element])")
}
}
var max = 0
print("dictionary -> ", dictionary)
for (key, value) in dictionary {
if value > max {
max = value
result = key
} else{
print("Not max value")
}
}
return result
}
// MARK: - PlayGround
mostCommonElement(inArray: colors)