最常见的数组元素 [英] Most common array elements

查看:120
本文介绍了最常见的数组元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to find the most common (modal) elements in an array.

我想到的最简单的方法是为每个唯一元素设置变量,并为每个元素分配一个计数变量,每次将其记录在遍历数组的for循环中时,计数变量都会增加.

The simplest way I could think of was to set variables for each unique element, and assign a count variable for each one, which increases every time it is recorded in a for loop which runs through the array.

不幸的是,数组的大小是未知的,并且会很大,因此该方法没有用.

Unfortunately the size of the array is unknown and will be very large, so this method is useless.

我在Objective-C中遇到了类似的问题,该问题使用NSCountedSet方法对数组元素进行排名.不幸的是,我对编程非常陌生,只能将第一行翻译成Swift.

I have come across a similar question in Objective-C that uses an NSCountedSet method to rank the array elements. Unfortunately I am very new to programming, and could only translate the first line into 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);

在我的程序中,我将需要在数组中找到前五个地名.

In my program I will need to find the top five place names in an array.

推荐答案

现在在Swift 2.0以下

edit: now with Swift 2.0 below

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

Not the most efficient of solutions but a simple one:

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 }

descending现在由成对的数组组成:值和频率, 最频繁的排序第一.因此,前5名"将是前5名 (假设有5个或更多不同的值).源数组有多大都没关系.

descending now consists of an array of pairs: the value and the frequency, sorted most frequent first. So the "top 5" would be the first 5 entries (assuming there were 5 or more distinct values). It shouldn't matter how big the source array is.

这是可以在任何序列上使用的通用函数版本:

Here's a generic function version that would work on any sequence:

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,您可以将该函数改编为协议扩展:


For Swift 2.0, you can adapt the function to be a protocol extension:

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:

For 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 }
    }
}

这篇关于最常见的数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆