Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/solr/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 最常见的数组元素_Arrays_Swift_Nscountedset - Fatal编程技术网

Arrays 最常见的数组元素

Arrays 最常见的数组元素,arrays,swift,nscountedset,Arrays,Swift,Nscountedset,我需要找到数组中最常见的(模态)元素 我能想到的最简单的方法是为每个唯一的元素设置变量,并为每个元素分配一个count变量,每次在数组中运行的for循环中记录时,该变量都会增加 不幸的是,数组的大小未知,并且将非常大,因此这种方法是无用的 我在Objective-C中遇到了一个类似的问题,它使用NSCountedSet方法对数组元素进行排序。不幸的是,我对编程非常陌生,只能将第一行翻译成Swift 建议的方法如下: var yourArray: NSArray! // My swift

我需要找到数组中最常见的(模态)元素

我能想到的最简单的方法是为每个唯一的元素设置变量,并为每个元素分配一个count变量,每次在数组中运行的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);
var yourray:NSArray!//我的快速翻译
NSCountedSet*set=[[NSCountedSet alloc]initWithArray:yourArray];
NSMutableDictionary*dict=[NSMutableDictionary new];
用于(集合中的id obj){
[dict setObject:[NSNumber NUMBER WITHINTEGER:[set countForObject:obj]]
forKey:obj];//键是日期
}
NSLog(@“Dict:%@”,Dict);
NSMUTABLEARRY*top3=[[NSMUTABLEARRY alloc]initWithCapacity:3];
//哪个dict obj=max
如果(dict.count>=3){

而(top3.count编辑:现在使用下面的Swift 2.0

不是最有效的解决方案,而是一个简单的解决方案:

let a = [1,1,2,3,1,7,4,6,7,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 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 }
    }
}

对于XCode 7.1,解决方案是

// Array of elements
let a = [7,3,2,1,4,6,8,9,5,3,0,7,2,7]

// Create a key for elements and their frequency
var times: [Int: Int] = [:]

// Iterate over the dictionary
for b in a {
    // Every time there is a repeat value add one to that key
    times[b] = (times[b] ?? 0) + 1
}

// This is for sorting the values
let decending = times.sort({$0.1 > $1.1})
// For sorting the keys the code would be 
// let decending = times.sort({$0.0 > $1.0})
// Do whatever you want with sorted array
print(decending)

与空速相同,在
中使用
减少
而不是

extension Sequence where Self.Iterator.Element: Hashable {
    func frequencies() -> [(Self.Iterator.Element, Int)] {
        return reduce([:]) {
            var frequencies = $0
            frequencies[$1] = (frequencies[$1] ?? 0) + 1
            return frequencies
        }.sorted { $0.1 > $1.1 }
    }
}
但是请注意,在这里,由于结构复制成本,所以您通常更喜欢使用
for in
的方式


[编辑:天哪,这篇文章是由同一个家伙写的,答案是第一名!]

你说的“前五名”是什么意思。您的数组多次包含相等的元素吗?您想知道最上面的元素吗?该数组将包含一个城市名称列表,用户在其中签入。我需要对数组中的元素进行排序,以输出用户最多签入的五个位置。因此,是的,数组中会有重复的元素多次注意,if-let-else可以简化为
frequency[x]=1+(frequency[x]??0)
Swift 3的语法是什么?
extension Sequence where Self.Iterator.Element: Hashable {
    func frequencies() -> [(Self.Iterator.Element, Int)] {
        return reduce([:]) {
            var frequencies = $0
            frequencies[$1] = (frequencies[$1] ?? 0) + 1
            return frequencies
        }.sorted { $0.1 > $1.1 }
    }
}