gpt4 book ai didi

arrays - 如何按最频繁点的顺序排列 CGPoint 数组

转载 作者:行者123 更新时间:2023-12-04 16:06:13 26 4
gpt4 key购买 nike

我看到了 this post
它展示了如何通过以下方式获取数组的最频繁值,例如整数:

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")
}

我想为 CGPoints 的数组实现相同的结果,这有点不同。我尝试使用相同的代码并得到一个错误:
Type 'CGPoint' does not conform to protocol 'Hashable'

在线
var counts = [CGPoint: Int]()

和一个错误
Value of type 'CGPoint' has no member '1'

在线
if let (value, count) = counts.max(isOrderedBefore: {$0.1 < $1.1}) {

如何按频率顺序排列 CGPoint 数组并打印一个带有值和出现次数的元组?

最佳答案

这行错误意味着什么:

Type 'CGPoint' does not conform to protocol 'Hashable'



是你不能用 CGPoint对象作为字典的键。

评论中提到的解决方法 Leo Dabus 应该可以很好地工作:使用您的 String 的调试描述( CGPoint )对象作为 counts 字典的键:
var counts = [String: Int]() 

myArray.forEach { counts[$0.debugDescription] = (counts[$0.debugDescription] ?? 0) + 1 }

if let (value, count) = counts.max(by: {$0.value < $1.value}) {
print("\(value) occurs \(count) times")
}

关于arrays - 如何按最频繁点的顺序排列 CGPoint 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41829278/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com