objective-c - 将 NSArray 中的元素映射到它们的计数并获得最频繁的

标签 objective-c algorithm collections nsarray

我正在做演示文稿,比较不同语言的标准库的集合和算法。帮助我编写这个问题的有效且可读的算法:

元编程语言:

struct Tweet { id, time, text, url, user_id };
struct User { id, name, nick };
array<Tweet> tweets;
map<int, User> userDict;

问题:

找到发送最多推文且 url 字段不等于 nil 的用户名。 还可以找到来自该用户的此类推文的计数。

我是这样开始的:

NSMutableDictionary * countByUserId = [NSMutableDictionary dictionary];
foreach (Tweet * tweet in tweets)
    if (tweet.url != 0)
        countByUserId[tweet->user_id] = @(countByUserId[tweet->user_id] + 1);

现在我需要找到具有最大值的键值。

这是我的 C++ 代码:

map<int,int> countByUserId;
for (auto it = tweets.begin(); it != tweets.end(); ++it)
    if (it->url != 0)
        countByUserId[it->user_id]++;

auto para = max_element(countByUserId.begin(),
                        countByUserId.end(),
                        [](pair<int,int> a, pair<int,int> b)
                        { return a.second < b.second; });

cout << "User = "  << userDict[para.first].name << endl
     << "Value = " << para.second << endl;

最佳答案

Now I need to find key-value with max value...

可能存在联系,因此您应该查找所有具有最大值的键值对。您可以在循环中计算最大值,然后再次遍历 NSDictionary,寻找它:

NSMutableDictionary * countByUserId = [NSMutableDictionary dictionary];
NSInteger max = -1;
foreach (Tweet * tweet in tweets) {
    if (tweet.url != 0) {
        int next = countByUserId[tweet->user_id].intValue + 1;
        countByUserId[tweet->user_id] = @(next);
        if (next > max) {
            max = next;
        }
    }
}
[countByUserId enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
    if ([obj intValue] == max) {
        NSLog(@"Found max for user: %@", key);
    }
}

关于objective-c - 将 NSArray 中的元素映射到它们的计数并获得最频繁的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20198189/

相关文章:

c++ - 了解 Getchar 解锁

java - 使用java处理多个csv行

objective-c - xib 中的预处理器指令?

ios - 如何使用for循环获取按钮标题

iphone - 正确使用 viewDidUnload

python - Karatsuba 的算法 : split the digit sequences about the middle

algorithm - 如何将重复键插入b树

java - 将 csv 字符串转换为带有双引号键/值的 Map

java - 按值的降序对 Map 进行排序

c++ - Objective-C 中调用方法与 C++ 有何不同?