Pick closest NSNumber from array

只谈情不闲聊 提交于 2019-12-04 20:02:53

In your post, the array is sorted. If it's always sorted, you can use binary search. NSArray has a convenient method for that:

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

Now there are four possibilities:

  1. Every element of values is larger than targetNumber: index is zero.
  2. Every element of values is smaller than targetNumber: index is values.count.
  3. values contains targetNumber: index is the index of targetNumber in values.
  4. index is the index of the smallest element of values that is greater than targetNumber.

I've cleverly listed the cases in the order we'll handle them. Here's case 1:

if (index == 0) {
    return [values[0] floatValue];
}

Here's case 2:

if (index == values.count) {
    return [[values lastObject] floatValue];
}

We can handle cases 3 and 4 together:

CGFloat leftDifference = targetNumber - [values[index - 1] floatValue];
CGFloat rightDifference = [values[index] floatValue] - targetNumber;
if (leftDifference < rightDifference) {
    --index;
}
return [values[index] floatValue];

If your values array is in order and you always want the value just larger than (or equal to) the entered value you could do something like this:

NSInteger count = 0;
do {
    count++;
} while (enteredNum > [values[count] intValue]);

// Do something with [values[count] intValue]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!