Taskinul Haque
Taskinul Haque

Reputation: 724

Objective C - comparing values in an array to an arbritary

How would you sort through an array, which also contains 0 values i.e.

and comparing it to a constant (say -5), which would return the index of the corresponding closest value (smallest difference) ? (i.e. closest value = -10, so returned value = 4)

The challenge here being 0 values should always be overlooked, and the array cannot be sorted before hand

Heres a Similar problem, answers for which doesn't quite work in my case How do I find the closest array element to an arbitrary (non-member) number?

Upvotes: 1

Views: 1451

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726509

That is relatively straightforward:

NSArray *data = @[@-54, @0, @-12, @0, @-10];
NSUInteger best = 0;
int target = -5;
for (NSUInteger i = 1 ; i < data.count ; i++) {
    int a = [[data objectAtIndex:best] intValue];
    int b = [[data objectAtIndex:i] intValue];
    if (b && abs(a-target) > abs(b-target)) { // Ignore zeros, check diff
        best = i;
    }
}
// At this point, "best" contains the index of the best match
NSLog(@"%lu",best); // Prints 4

Upvotes: 1

Related Questions