字典数组中每个对象的最大值

时间:2016-10-23 06:36:58

标签: ios objective-c arrays dictionary nspredicate

我有一系列字典,我试图获得阵列中每个玩家的最高分数。每个玩家可以有多个条目我试图获得每个玩家最佳分数的一系列词典。

的NSArray [0] - NSDictionary

        - [0] Score: (double)20.7
        - [1] NameID: (int) 1
        - [2] Date 

[1] - NSDictionary

        - [0] Score: (double)25
        - [1] NameID: (int) 1
        - [2] Date

[2] - NSDictionary

        - [0] Score: (double)28
        - [1] NameID: (int) 2
        - [2] Date 

[3] - NSDictionary`

        - [0] Score: (double)26
        - [1] NameID: (int) 3
        - [2] Date

我尝试过使用NSPredicate predicateWithFormat,但我只能恢复数组中与名称无关的所有内容的最大值。

预期输出:

的NSArray [1] - NSDictionary

        - [0] Score: (double)25
        - [1] NameID: (int) 1
        - [2] Date

[2] - NSDictionary

        - [0] Score: (double)28
        - [1] NameID: (int) 2
        - [2] Date 

[3] - NSDictionary`

        - [0] Score: (double)26
        - [1] NameID: (int) 3
        - [2] Date

感谢您的帮助。

6 个答案:

答案 0 :(得分:2)

您不能使用NSPredicate,因为您想确定几个不同玩家的最高分数。在幕后,NSPredicate无论如何都要迭代数组,因此使用自己的循环效率并不高。在下面的代码中,我假设分数和玩家名称包含在NSNumber

-(NSArray *)maxScoresForPlayers:(NSArray *)playerScores {

    NSMutableDictionary *maxScores = [NSMutableDictionary new];

    for (NSDictionary *player in playerScores) {
        NSNumber *playerID = (NSNumber *)player[@"NameID"];
        NSDictionary *playerMax = maxScores[playerID];
        if (playerMax == nil) {
           playerMax = player;
        } else {
           NSNumber *currentMax = (NSNumber *)[playerMax[@"Score"];
           NSNumber *playerScore = (NSNumber *)player[@"Score"];
           if ([playerScore doubleValue] > [currentMax doubleValue]) {
                playerMax = player;
           }
        }
        maxScores[playerID] = playerMax;
    }

    return([maxScores allValues];
}

答案 1 :(得分:1)

你可以像这样手动完成:

NSMutableDictionary *maxScoresDict = [NSMutableDictionary dictionary];
for (NSDictionary *score in scoresArray) {
    NSNumber *key = score[@"NameID"];
    NSNumber *savedMax = maxScoresDict[key][@"Score"];
    NSNumber *currentMax = maxScoresDict[key][@"Score"];
    if (savedMax == nil || [currentMax doubleValue] > [savedMax doubleValue]) {
        maxScoresDict[key] = score;
    }
}
NSArray *maxScoresArray = [maxScoresDict allValues];

答案 2 :(得分:0)

试试这个:

NSArray *objects = @[@{@"Score": @(20.7),
                       @"NameID": @(1),
                       @"Date": [NSDate date]},
                     @{@"Score": @(25),
                       @"NameID": @(1),
                       @"Date": [NSDate date]},
                     @{@"Score": @(28),
                       @"NameID": @(2),
                       @"Date": [NSDate date]},
                     @{@"Score": @(26),
                       @"NameID": @(3),
                       @"Date": [NSDate date]}];
NSMutableArray *users = [NSMutableArray array];

for (NSInteger i=0; i<objects.count; i++) {

    NSDictionary *dict = objects[i];
    NSNumber *nameID = dict[@"NameID"];

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self.NameID==%@", nameID];
    NSInteger index = [users indexOfObjectPassingTest:^BOOL(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        BOOL found = [predicate evaluateWithObject:obj];
        return found;
    }];

    if (index != NSNotFound) {
        NSNumber *score1 = dict[@"Score"];
        NSNumber *score2 = users[index][@"Score"];

        if (score1.doubleValue > score2.doubleValue) {
            [users replaceObjectAtIndex:index withObject:dict];
        }
    }
    else {
        [users addObject:dict];
    }
}
NSLog(@"%@", users);

答案 3 :(得分:0)

- (NSArray *)getBestScores:(NSArray *)players {
    NSMutableDictionary *best = [[NSMutableDictionary alloc] init];
    for (NSDictionary *p in players) {
        NSDictionary *b = [best valueForKey:[p valueForKey:@"NameID"]];
        if (!b || [[p valueForKey:@"Score"] doubleValue] > [[b valueForKey:@"Score"] doubleValue])
            [best setValue:p forKey:[p valueForKey:@"NameID"]];
    }
    return [best allValues];
}

答案 4 :(得分:0)

// Get Max Value of integer element from Array of Dictonaries.
// Example Array Starts

<paramArray>(
{
DicID = 1;
Name = "ABC";
ValuetoCalculateMax = 2800;
},
{
DicID = 2;
Name = "DEF";
ValuetoCalculateMax = 2801;
},
{
DicID = 3;
Name = "GHI";
ValuetoCalculateMax = 2805;
}
)
// Example Array Ends

// Implementation


int   MaxintegerValue=0;

MaxintegerValue=[self getMaxValueFromArrayofDictonaries:paramArray];

// Implementation Ends


// Function Starts

-(int)getMaxValueFromArrayofDictonaries:(NSArray *)paramArray
{
int MaxValue=0;
NSMutableDictionary  *dic=[[NSMutableDictionary alloc]init];
for ( int i=0; i<[paramArray count]; i++ )
{
    dic=[paramArray objectAtIndex:i];
    if ([[dic valueForKey:@"ValuetoCalculateMax"] intValue] > MaxValue)
    {
        MaxValue=[[dic valueForKey:@"ValuetoCalculateMax"] intValue];
    }
    else
    {
        MaxValue=MaxValue;
    }
    }
   return MaxValue;
}

// Function Ends

答案 5 :(得分:-1)

您需要做的是为每个用户找到分数,然后找出最大分数。

- (void)findMaxScoreForUser:(int)userId {

NSDictionary *dict0 = [NSDictionary dictionaryWithObjects:@[@27.0,@3] forKeys:@[@"Score",@"UserID"]];
NSDictionary *dict1 = [NSDictionary dictionaryWithObjects:@[@25.0,@2] forKeys:@[@"Score",@"UserID"]];
NSDictionary *dict2 = [NSDictionary dictionaryWithObjects:@[@23.0,@3] forKeys:@[@"Score",@"UserID"]];

NSArray *arr = [NSArray arrayWithObjects:dict0,dict1,dict2, nil];
NSMutableArray *scores = [NSMutableArray array];
for (NSDictionary *dict in arr) {
    int userID = [[dict valueForKey:@"UserID"] intValue];
    if (userId == userID) {
        [scores addObject:[dict valueForKey:@"Score"]];
    }
}

int max = [[scores valueForKeyPath:@"@max.intValue"] intValue];

}