Robert
Robert

Reputation: 38213

What structure should I use to store these objects?

I am trying to implement something similar to the flight control game. There will be a set of objects representing planes that get spawned and removed 'randomly'. Individual planes can then get touched and will respond. The model should take a plane index as a parameter when something get touched.

My storage requirements are:

  1. Need fast iteration over all elements
  2. Need fast insertion / deletion
  3. Need to look up and item quickly by index

    • What should I use? NSMutableArray, NSMutableSet ?
    • Should I store each object in two places? (e.g. Set for fast iteration, Array for fast lookup)?

Upvotes: 0

Views: 102

Answers (2)

Juraj Blaho
Juraj Blaho

Reputation: 13461

NSMutableArray is good enough if you want to look up only by index. The problem may be the deletion which takes O(n). When you do not need the index persistence you may delete in O(1) by placing the last item to the item deleted and shorten the array by 1.

Storing at two places would be slow in this case, because it would not bring any advantage in searching speed, but would require to maintain two containers.

Upvotes: 1

bwawok
bwawok

Reputation: 15357

Storing in 2 places seems silly. An Array should be fine, with o(n) iteration, o(1) look up by index. I am not familiar with objective-c to know the deletion or insertion speed, but both should be plenty fast if some system level array copy facilities are used.

Upvotes: 0

Related Questions