Saturday, June 1, 2013

NSArray NSBinarySearchingLastEqual example in Objective C (iOS).


NSArray NSBinarySearchingLastEqual

NSBinarySearchingOptions
Options for searches and insertions using indexOfObject:inSortedRange:options:usingComparator:.

enum {
NSBinarySearchingFirstEqual = (1 << 8),
NSBinarySearchingLastEqual = (1 << 9),
NSBinarySearchingInsertionIndex = (1 << 10),
};
typedef NSUInteger NSBinarySearchingOptions;
Constants
NSBinarySearchingFirstEqual
Specifies that the search should return the first object in the range that is equal to the given object.
NSBinarySearchingLastEqual
Specifies that the search should return the last object in the range that is equal to the given object.
NSBinarySearchingInsertionIndex
Returns the index at which you should insert the object in order to maintain a sorted array.

NSArray NSBinarySearchingLastEqual example.
You can define a block as a global variable to get an effect similar to functions.

NSComparisonResult (^globalBlock)(id,id) = ^(id lhs, id rhs) {
    if([lhs intValue] < [rhs intValue]) {
        return (NSComparisonResult)NSOrderedAscending;
    } else if([lhs intValue] > [rhs intValue]) {
        return (NSComparisonResult)NSOrderedDescending;
    }
    return (NSComparisonResult)NSOrderedSame;
};
Then, in the method doing the comparison:

int index1 = [array indexOfObject:number
                    inSortedRange:NSMakeRange(0, [array count])
                          options: NSBinarySearchingLastEqual
                  usingComparator:globalBlock];
To put the block in a header, for external use:

NSComparisonResult (^globalBlock)(id,id);

Example of [NSArray NSBinarySearchingLastEqual].
CGFloat targetNumber = mySlider.value;
NSUInteger index = [values indexOfObject:@(targetNumber)
    inSortedRange:NSMakeRange(0, values.count)
    options: NSBinarySearchingLastEqual | NSBinarySearchingInsertionIndex
    usingComparator:^(id a, id b) {
        return [a compare:b];
    }];

NSArray NSBinarySearchingLastEqual example.
-(id) /* Getting */
{
    int location = [array indexOfObject:node
                                    inSortedRange:NSMakeRange(0, array.count)
                                          options: NSBinarySearchingLastEqual
                                  usingComparator:
                          ^ NSComparisonResult(id obj1, id obj2)
                          {
                              if (obj1.valueToCompare < obj2.valueToCompare) return NSOrderedAscending;
                              if (obj1.valueToCompare > obj2.valueToCompare) return NSOrderedDescending;
                              else return NSOrderedSame;
                          }];
    if (location == NSNotFound) return nil;
    return [array objectAtIndex:location];
}

End of NSArray NSBinarySearchingLastEqual example article.