在NSArray的NSArray中的Sum objectAtIndex值或在NSDictionary中为key添加值

时间:2015-04-03 13:07:09

标签: ios objective-c arrays nsdictionary

我需要的任何一种解决方案。建议我最好的答案。

我有数百个这样的阵列给我最好的解决方案。我不喜欢嵌套 ForLoops

1 即可。我需要Distinct Union Array By ObjectAtIndex:0,并且它们在ObjectAtIndex:1中求和它们的值。

A - &GT; [[1,&#34; 100.0&#34;],[2,&#34; 100.0&#34;],[2,&#34; 100.0&#34;],[3,&#34; 100.0&#34;],[4,&#34; 100.0&#34;],[3,&#34; 100.0&#34;],[4,&#34; 100.0&#34;]] < / p>

乙 - &GT; [[1250],[2250],[1250],[3,&#34; 200.2&#34;],[1,&#34; 200.2&#34;],[4,&#34; 200.2& #34;],[1,&#34; 200.2&#34;],[4,&#34; 200.2&#34;]]

我需要A--> [[1,"100.0"],[2,"200.0"],[3,"200.0"],[4,"200.0"]]

2 。我必须在Dictionary中设置对象A和B数组。但是,如果密钥存在于字典中,则该值与退出值一致。

{

 A =     {
    1 = 100;
    2 = 100;
    3 = 100;
    4 = 100;
};

 B =     {
    1 = 250;
    2 = 250;
    3 = "200.2";
    4 = "200.2";
};

}

NSArray* uniqueValues = [data valueForKeyPath:[NSString stringWithFormat:@"@distinctUnionOfObjects.%@", @"self"]];

2 个答案:

答案 0 :(得分:1)

NSArray* A = @[@[@1, @100.0],@[@2, @100.0],@[@3, @100.0],@[@1, @100.0],@[@1, @100.0]];

NSMutableDictionary* sum = [NSMutableDictionary new];
for (NSArray* item in A)
{
    id key = item[0];
    if (sum[key] == nil)
    {
        sum[key] = item[1];
    }
    else
    {
        sum[key] = @([sum[key] floatValue] + [item[1] floatValue]);
    }
}

NSLog(@"%@", sum.description);

输出:

3 = 100;
1 = 300;
2 = 100;

答案 1 :(得分:0)

基于KVC Collection Operators的替代解决方案。

    NSArray* arrayOFArray = @[@[@1, @100.0],@[@2, @100.0],@[@3, @100.0],@[@1, @100.0],@[@1, @100.0]];

    NSMutableDictionary* sumDic = [NSMutableDictionary new];
    NSInteger index = 0; // By changing index position. You get unique sum either way.
    for (NSArray* item in arrayOFArray)
    {
       id key = item[index];
        if (key && sumDic[key] == nil) {

            NSArray *keyArray = [self findSameValueKey:arrayOFArray WithKey:key withIndex:index];
            NSArray *unionArray = [keyArray valueForKeyPath: @"@unionOfArrays.self"];
            NSNumber *sum = [unionArray valueForKeyPath:@"@sum.floatValue"];
            sumDic[key] = [NSNumber numberWithInt:[sum floatValue] - ([keyArray count]* [key floatValue])];
        }
    }

    NSLog(@"%@", sumDic.description);


    // Helps to find same value key.
    -(NSArray*)findSameValueKey:(NSArray*)dateArray WithKey:(NSString*)key withIndex:(NSInteger)index {
        NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(NSArray *resultsArray, NSDictionary *bind){
            if ([resultsArray[index] isEqual:key]) {
                return true;
            }
            return false;
        }];

        // Apply the predicate block .
        NSArray *sameValueKeys = [dateArray filteredArrayUsingPredicate:predicate];
        return sameValueKeys;
    }