I saw this post which showed how to get the most frequent value of an array, for example, integers as follows:
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 most frequent value and its count with max(isOrderedBefore:) if let (value, count) = counts.max(isOrderedBefore: {$0.1 < $1.1}) { print("\(value) occurs \(count) times") }
I want to achieve the same result for an array of CGPoints
, this is a little different. I tried using the same code and got an error:
Type 'CGPoint' does not conform to protocol 'Hashable'
in line
var counts = [CGPoint: Int]()
and mistake
Value of type 'CGPoint' has no member '1'
in line
if let (value, count) = counts.max(isOrderedBefore: {$0.1 < $1.1}) {
How can I arrange a CGPoint array in frequency and print order, say a tuple with the value and the amount of time it appears?
source share