大佬教程收集整理的这篇文章主要介绍了数组 – 最常见的数组元素,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我能想到的最简单的方法是为每个唯一元素设置变量,并为每个元素分配一个计数变量,每次在一个贯穿数组的for循环中记录它时都会增加.
不幸的是,数组的大小是未知的并且将非常大,因此这种方法是无用的.
我在Objective-C中遇到了一个类似的问题,它使用NSCountedSet方法对数组元素进行排名.不幸的是,我对编程非常陌生,只能将第一行翻译成Swift.
建议的方法如下:
var yourArray: NSArray! // My swift translation NSCountedSet *set = [[NSCountedSet alloc] initWithArray:yourArray]; NSMutableDictionary *dict=[NSMutableDictionary new]; for (id obj in set) { [dict setObject:[NSNumber numberWithInteger:[set countForObject:obj]] forKey:obj]; //key is date } NSLog(@"Dict : %@",dict); NSMutableArray *top3=[[NSMutableArray alloc]initWithCapacity:3]; //which dict obj is = max if (dict.count>=3) { while (top3.count<3) { NSInteger max = [[[dict allValues] valueForKeyPath:@"@max.intValue"] intValue]; for (id obj in set) { if (max == [dict[obj] integerValue]) { NSLog(@"--> %@",obj); [top3 addObject:obj]; [dict removeObjectForKey:obj]; } } } } NSLog(@"top 3 = %@",top3);
在我的程序中,我需要在数组中找到前五个地名.
let a = [1,1,2,3,7,4,6,2] var frequency: [Int:Int] = [:] for x in a { // set frequency to the current count of this element + 1 frequency[x] = (frequency[x] ?? 0) + 1 } let descending = sorted(frequency) { $0.1 > $1.1 }
现在降序由一对数组组成:值和频率,
首先排序最频繁.所以“前5名”将是前5个参赛作品
(假设有5个或更多不同的值).源阵列有多大并不重要.
func frequencies <S: SequenceType where S.Generator.Element: Hashable> (source: S) -> [(S.Generator.Element,Int)] { var frequency: [S.Generator.Element:Int] = [:] for x in source { frequency[x] = (frequency[x] ?? 0) + 1 } return sorted(frequency) { $0.1 > $1.1 } } frequencies(a)
对于Swift 2.0,您可以将该功能调整为协议扩展:
extension SequenceType where Generator.Element: Hashable { func frequencies() -> [(Generator.Element,Int)] { var frequency: [Generator.Element:Int] = [:] for x in self { frequency[x] = (frequency[x] ?? 0) + 1 } return frequency.sort { $0.1 > $1.1 } } } a.frequencies()
对于Swift 3.0:
extension Sequence where Self.Iterator.Element: Hashable { func frequencies() -> [(Self.Iterator.Element,Int)] { var frequency: [Self.Iterator.Element:Int] = [:] for x in self { frequency[x] = (frequency[x] ?? 0) + 1 } return frequency.sorted { $0.1 > $1.1 } } }
以上是大佬教程为你收集整理的数组 – 最常见的数组元素全部内容,希望文章能够帮你解决数组 – 最常见的数组元素所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。