aignetti - 3 months ago 20x

Swift Question

i have an Array of numbers and i want to know which number is most frequent in this array. The array sometimes has 5-6 integers, sometimes it has 10-12, sometimes even more - also the integers in the array can be different. So i need a function which can work with different lengths and values of an array.

One example:

myArray = [0, 0, 0, 1, 1]

Another example:

myArray = [4, 4, 4, 3, 3, 3, 4, 6, 6, 5, 5, 2]

Now im searching for a function which gives out 0 (in the first example) as Integer, as it is 3 times in this array and the other integer in the array (1) is only 2 times in the array. Or for the second example it would be 4.

It seems pretty simple, but i cannot find a solution for this. Found some examples in the web, where the solution is to work with dictionaries or where the solution is simple - but i cannot use it with Swift 3 it seems...

However, i did not find a solution which works for me. Someone has an idea how to get the most frequent integer in an array of integers?

Thank you guys.

Answer

```
let myArray = [4, 4, 4, 3, 3, 3, 4, 6, 6, 5, 5, 2]
// Create dictionary to map value to count
var counts = [Int: Int]()
// Count the values with using forEach
myArray.forEach { counts[$0] = (counts[$0] ?? 0) + 1 }
// Find the maximum value and its count with max(isOrderedBefore:)
if let (max, count) = counts.max(isOrderedBefore: {$0.1 < $1.1}) {
print("\(max) occurs \(count) times")
}
```

Output:

`4 occurs 4 times`

Here it is as a function:

```
func maxValue(array: [Int]) -> (maxiumum: Int, count: Int)? {
var counts = [Int: Int]()
array.forEach { counts[$0] = (counts[$0] ?? 0) + 1 }
if let (max, count) = counts.max(isOrderedBefore: {$0.1 < $1.1}) {
return (max, count)
}
// array was empty
return nil
}
if let (max, count) = maxValue(array: [1, 3, 2, 1, 1, 4, 5]) {
print("\(max) occurs \(count) times")
}
```

`1 occurs 3 times`

Source (Stackoverflow)

Comments