JKT - 10 months ago 34

Swift Question

Given an array that consists of arrays containing integers.

`[[2], [3], [2, 2], [5], [7], [2, 2, 2], [3, 3]]`

What would be the preferred way in Swift to remove the arrays that contains a smaller number of elements with a certain value and keep only the larger arrays containing that value.

The result from the input above would be

`[[5], [7], [2, 2, 2], [3, 3]]`

Answer

Use a `[Int: [Int]]`

dictionary to keep track of the largest array for the value specified by the key.

```
let arrays = [[2], [3], [2, 2], [5], [7], [2, 2, 2], [3, 3]]
var largest = [Int: [Int]]()
for arr in arrays {
// Get the first value from the array
if let first = arr.first {
// current is the count for that key already in dictionary largest
// If the key isn't found, the nil coalescing operator ?? will
// return the default count of 0.
let current = largest[first]?.count ?? 0
// If our new array has a larger count, put it in the dictionary
if arr.count > current {
largest[first] = arr
}
}
}
// Convert the dictionary's values to an array for the final answer.
let result = Array(largest.values)
print(result) // [[5], [7], [2, 2, 2], [3, 3]]
```

**Alternate Version**

This version uses a `[Int: Int]`

dictionary to just keep the counts of the largest array found for each key, and then reconstructs the arrays at the end using an array constructor.

```
let arrays = [[2], [3], [2, 2], [5], [7], [2, 2, 2], [3, 3]]
var counts = [Int: Int]()
for arr in arrays {
if let first = arr.first {
counts[first] = max(counts[first] ?? 0, arr.count)
}
}
let result = counts.map { [Int](count: $1, repeatedValue: $0) }
print(result) // [[5], [7], [2, 2, 2], [3, 3]]
```