1

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

  • -54
  • 0
  • -12
  • 0
  • -10

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?

Community
  • 1
  • 1
Taskinul Haque
  • 724
  • 2
  • 15
  • 36
  • Is this a regular C array, or an `NSArray`? – Sergey Kalinichenko Sep 26 '12 at 09:49
  • The restriction on sorting needs some explanation... Are you trying to keep this array synced with another array? Using the array index as an implicit data value often leads to pain -- maybe it's time to rethink your data structure. – Caleb Sep 26 '12 at 10:06

1 Answers1

1

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
Sergey Kalinichenko
  • 697,062
  • 78
  • 1,055
  • 1,465