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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With