tags:

views:

17

answers:

2

I have an NSMutableArray of Sprites and I want to remove a few of them based on their proximity to another sprite. So say I have 10 sprites and I want to remove the first 3 that are closest to another sprite.

I can't think of a sophisticated efficient way of doing this, anything i've come up with so far seems overly convoluted and inefficient. Any ideas?

+1  A: 

Assuming no special data structures or order, you can iterate through each element of your NSMutableArray, keeping track of the indices and distances of the 3 closest sprites in a second NSMutableArray, ordered by increasing distance. Whenever you find a sprite closer than the third element of your temporary array, you drop the third element and insert the index and distance of this new sprite in the array. It's a little tricky, but should be fairly efficient.

If you want to get fancy, you can use a more complex data structure to bucket sprites together based on their location. For 10 sprites that seems like it would be a lot more bother than it's worth.

Hilton Campbell
Ye thats pretty much what I had in mind, was just wondering if there was any functions associated with NSMutableArray that I could take advantage of. Thanks for the help.
Tiddly
A: 

If you can, you can also keep keep that array of sprites sorted based on the distance. This would not work in a game where things are constantly moving around on the screen of course, but it might work in other situations. Then you can simply take the first three items of the array. (Assuming that they are sorted by distance, longest distance first)

St3fan