Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Finding nearest time - return index of array

I am looking to find the nearest time out of an array. My time in jSON is returned as milliseconds (epoch) - tideSummary.date.epoch

Stuck on the logic to find the closest time in the array compared to the current time. I can then grab that index and display the specific information. Thoughts on how I would do this?

So far I have:

  • Return the current time in ms as NSTimeInterval
  • Use that to find the delta of current time and tide[i] time

I would need to store the min somehow and return only the smallest delta value correct?

Any ideas?

1 Answer

Yes, smallest delta is good (you may also want to take absolute value as well).

NSTimeInterval by default is meant to be used as seconds, with sub-second intervals represented by subsequent decimal places. Best to stick to that for better documentation purposes.

A simply way to find the min would be a linear search: you iterate through the array, store the minimum (absolute) delta thus far and its corresponding index. Then when you hit the end, you have the min. Here's a somewhat self-explanatory code doing just that (assuming array stores NSDate objects as well)

NSTimeInterval minDelta = DBL_MAX; // largest double value
NSInteger minIndex = NSNotFound;
for ( NSInteger index = 0; i<array.count; i++ ) {
  NSTimeInterval newDelta = fabs( [(NSDate *)array[i] timeIntervalSinceNow]);
  if ( newDelta < minDelta ) {
    minDelta = newDelta;
    minIndex = index;
  } 
}

There's a slightly more Objective-C-esque way of doing this with NSPredicate, but that's probably too messy to explain here. Plus this code is probably more educational for you at this point.