算法:在NSDictionary中保持键/值对的计数

时间:2008-11-21 03:04:36

标签: iphone c objective-c cocoa algorithm

对Cocoa不熟悉,并且可能不知道已经将这些功能整齐地包含在OO类中的所有可用类,这里是一个算法查询。计算特定密钥在多个NSDictionary个实例的数组中出现的次数的最佳选择是什么?

基本上,我的数据结构(在本例中为NSArray)可能在任何给定时间包含多个NSDictionary个实例,每个实例具有相同的键,可能具有不同的值。一些值重复。我希望能够知道特定键/值出现的次数。例如:

{
  foo => 1,
  bar => 2
}
{
  foo => 1,
  bar => 3
}
{
  foo => 2,
  bar => 1
}

在这种情况下,我感兴趣foo=>1发生了2次,foo=>2发生了1次。构建NSCountedSet的实例是最好的方法吗?也许是一个C链表?

3 个答案:

答案 0 :(得分:4)

您可能想重新考虑如何构建数据。我会在添加到NSArray时跟踪这样的事情,而不是试图在以后发现它。您可以创建一个新类来处理添加和删除数据,以便您可以保留自己的数据计数。

答案 1 :(得分:2)

NSDictionary * dict1 = [[NSDictionary alloc] initWithObjectsAndKeys:
                        [NSNumber numberWithInt:1], @"foo",
                        [NSNumber numberWithInt:2], @"bar", nil];
NSDictionary * dict2 = [[NSDictionary alloc] initWithObjectsAndKeys:
                        [NSNumber numberWithInt:1], @"foo",
                        [NSNumber numberWithInt:3], @"bar", nil];
NSDictionary * dict3 = [[NSDictionary alloc] initWithObjectsAndKeys:
                        [NSNumber numberWithInt:2], @"foo",
                        [NSNumber numberWithInt:1], @"bar", nil];
NSArray * arrayOfDictionaries = [[NSArray alloc] initWithObjects:
                                 dict1, dict2, dict3, nil];

// count all keys in an array of dictionaries (arrayOfDictionaries):

NSMutableDictionary * countKeys = [[NSMutableDictionary alloc] initWithCapacity:0];
NSCountedSet * counts = [[NSCountedSet alloc] initWithCapacity:0];

NSArray * keys;
NSString * pairString;
NSString * countKey;
for (NSDictionary * dictionary in arrayOfDictionaries)
{
    keys = [dictionary allKeys];
    for (NSString * key in keys)
    {
        pairString = [NSString stringWithFormat:@"%@->%@", key, [dictionary valueForKey:key]];
        if ([countKeys valueForKey:pairString] == nil)
        {
            [countKeys setValue:[NSString stringWithString:pairString] forKey:pairString];
        }
        countKey = [countKeys valueForKey:pairString];
        { [counts addObject:countKey]; }
    }
}

NSLog(@"%@", counts);

[counts release];
[countKeys release];

[arrayOfDictionaries release];
[dict1 release];
[dict2 release];
[dict3 release];

答案 2 :(得分:1)

NSCountedSet *keyCounts = [NSCountedSet set];
for (NSDictionary *dict in myDictionaries)
    [keyCounts unionSet:[NSSet setWithArray:[dict allKeys]]];