开发者

Objective-C: most efficient way to map from number to according NSRange in NSDictionary

开发者 https://www.devze.com 2023-04-12 18:02 出处:网络
I\'ve got a lot of objects with according ranges: Object1 => 0 - 23 Object2开发者_如何学Python => 24 - 84

I've got a lot of objects with according ranges:

Object1 => 0 - 23
Object2开发者_如何学Python => 24 - 84
Object3 => 85 - 103
...

Those ranges vary, now I'm looking for the most efficient way in Objective-C to say "okay, I've got the number 56; which object has the according range? Ah, yes: it's Object2".

Any ideas? Binary search? Something else?

Thanks a lot!


It looks pretty much like finding the position of a specified value in a sorted list of the different points of your segment, in your case you can take for example : [-0.5,23.5,84.5,103.5] it's the list of the midpoint between start and end of each segment.

if position of you specified value is 1 => object 1

if it's 2 => object2

if it's 3 => object 3

For 56 you would get 2 => object 2

hope it helps


Edit :

For an array A of size N, the pseudo code for this modified binary search would be.

  min := 0; //my array start at index 0
  max := N-1; 
  repeat
    mid := (min+max) div 2;
    if x > A[mid] then
      min := mid + 1;
    else
      max := mid - 1;
  until (A[mid+1] > x >A[mid]) or (min > max);
  return mid+1

I modified the condition until (cf wikipedia article on binary search) to fit the constraint of the problem. I am modifying the mid until x is between 2 elements and I return mid+1

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号