Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Sort the existing array of values "indirectly", using an array of indexes, and sorting by the "distance" to the search value. The first three items after the sort are the "nearest" values. </p> <p>Example:</p> <pre><code>#import &lt;Foundation/Foundation.h&gt; @interface NearestSearcher : NSObject { } + (NSArray *) searchNearestValuesOf: (int) value inArray: (NSArray *) values; @end @implementation NearestSearcher + (NSArray *) searchNearestValuesOf: (int) value inArray: (NSArray *) values { // set up values for indexes array NSMutableArray *indexes = [NSMutableArray arrayWithCapacity: values.count]; for (int i = 0; i &lt; values.count; i++) [indexes addObject: [NSNumber numberWithInt: i]]; // sort indexes [indexes sortUsingComparator: ^NSComparisonResult(id obj1, id obj2) { int num1 = abs([[values objectAtIndex: [obj1 intValue]] intValue] - value); int num2 = abs([[values objectAtIndex: [obj2 intValue]] intValue] - value); return (num1 &lt; num2) ? NSOrderedAscending : (num1 &gt; num2) ? NSOrderedDescending : NSOrderedSame; }]; return [indexes subarrayWithRange: NSMakeRange(0, 3)]; } @end // DEMO #define NUM_VALUES 20 int main (int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; // DEMO SETUP // set up values array with random values NSMutableArray *values = [NSMutableArray arrayWithCapacity: NUM_VALUES]; for (int i = 0; i &lt; NUM_VALUES; i++) [values addObject: [NSNumber numberWithInt: arc4random() % 200]]; // display values array for (int i = 0; i &lt; values.count; i++) NSLog(@"%2d: %4d", i, [[values objectAtIndex: i] intValue]); // get a random value for x int x = arc4random() % 200; // METHOD INVOCATION NSArray *results = [NearestSearcher searchNearestValuesOf: x inArray: values]; // SHOW RESULTS NSLog(@"------------------------"); NSLog(@"x: %d", x); for (NSNumber *num in results) NSLog(@"%@: %@", num, [values objectAtIndex: [num intValue]]); [pool drain]; return 0; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload