Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to locate maximum value and position in NSMutableArray

I need to search a mutable array for the maximum value and return its position as well as value. I'd only like to iterate through the array once and I'm not sure if that's possible

an example of what I'm trying to accomplish can be demonstrated below

    NSMutableArray *array = [[NSMutableArray alloc] init];
    for (int i = 0; i<20; i++)
        [array addObject:[NSNumber numberWithInteger:(arc4random()%200)]];

    NSObject *max = [array valueForKeyPath:@"@max.self"];

the max object only seems to contain the value (and not the position). this can be demonstrated through the debugger with print-object max

Any advice out there?

like image 745
Rasman Avatar asked May 24 '26 09:05

Rasman


1 Answers

Using valueForKeyPath:@"@max.self" is great, but only if you want the maximum value.

To know both index and value in one iteration, I'd use enumerateWithBlock:

NSMutableArray *array = [[NSMutableArray alloc] init];
for (int i = 0; i<20; i++)
    [array addObject:[NSNumber numberWithInteger:(arc4random()%200)]];

__block NSUInteger maxIndex;
__block NSNumber* maxValue = [NSNumber numberWithFloat:0];
[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    NSNumber* newValue = obj;
    if ([newValue isGreaterThan:maxValue]) {
        maxValue = newValue;
        maxIndex = idx;
    }
}];

Quite more code, but you're iterating only once in the array.

like image 124
gcamp Avatar answered May 30 '26 17:05

gcamp