简体   繁体   中英

Return value closest to 0 including negative numbers

I have an NSDictionary which I would like to return the corresponding key nearest zero (including those with negative numbers):

NSDictionary *dict = @{
                       @"David" : @-89,
                       @"Bobby" : @61,
                       @"Nancy" : @-8,
                       @"Sarah" : @360,
                       @"Steve" : @203
                      };

So in this case Nancy would be closest... How can I do that? I searched but came up empty.

It is a simple max min problem,

NSString *curMinKey = [dict.allKeys firstObject];
NSInteger curMinVal = ABS([[dict objectForKey:curMinKey] integerValue]);
for(id key in dict) {
    if(curMinVal > ABS([[dict objectForKey:key] integerValue])) {
        curMinKey = key;
        curMinVal = ABS([[dict objectForKey:key] integerValue]);
    }
}
/// curMinKey is what you are looking for

Simply iterate the values and keep track of which one is closest to zero. Use abs to work with absolute values.

Disclaimer - below code is not tested - could be typos. It also assumes integers. Adjust as needed to support floating point values.

NSDictionary *dict = ... // your dictionary
NSInteger closestValue = NSIntegerMax;
NSString *closestKey = nil;
for (NSString *key in [dict allKeys]) {
    NSNumber *value = dict[key];
    NSInteger number = (NSInteger)labs((long)[value integerValue]);
    if (number < closestValue) {
        closestValue = number;
        closestKey = key;
    }
}

NSLog(@"Closest key = %@", closestKey);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM