algorithm - Picking JSON objects out of array based on their value -


perhaps think wrong, here problem:

i have nsmutablearray full of json objects. each object this, here 2 of them example:

{ player = "lorenz"; speed = "12.12"; },  { player = "firmino"; speed = "15.35"; } 

okay fine, dynamic info webserver feed. want though lets pretend there 22 such entries, , speeds vary.

i want have timer going starts @ 1.0 seconds , goes 60.0 seconds, , few times second want grab players speed has been passed. instance if timer goes off @ 12.0 , , goes off again @ 12.5, want grab out player names between 12.0 , 12.5 in speed, see?

the obvious easy way iterate on array every time timer goes off, timer go off lot, 10 times second or more, wasteful algorithm think. better ideas? attempt alter way data comes webserver don't feel should necessary.

note: edited reflect corrected understanding number in 1 60 incremented continously across range rather being random number in interval.

before enter timer loop, should common preprocessing:

  1. convert speeds strings numeric values upfront fast comparison without having parse each time. o(1) each item , o(n) process items.

  2. put data in ordered container such sorted list or sorted binary tree. allow find elements in target range. o(n log n) sort items.

on first iteration:

  • use binary search find start index. o(log n).
  • use binary search find end index, using start index bound search.

on subsequent iterations:

  • if each iteration increases predictable amount , step between elements in list likewise predictable amount, maintain pointer , increment per pete's comment. make each iteration cost o(1) (just stepping ahead fixed amount).

  • if steps between iterations and/or entries in list not predictable, binary search in initial case. if values monotonically increasing (as understand problem stating), if unpredictable, can incorporate binary search algorithm maintaining index in other case, instead of resuming iteration directly there, if values unpredictable, instead use remembered index set lower bound on binary search narrow region being searched. make each iteration cost o(log m), "m" remaining elements considered.

overall, produces algorithm no worse o((n + i) log n) "i" number of iterations compared previous algorithm o(i * n) (and shifts of computation outside of loop, rather inside loop).


Comments