I have this NSMutableArray which is a collection of objects that are being moved on the screen. When an object intersects another one, I need to construct an array with this object intersected. If this object is by itself intersecting with another, this one must be included in that array and so on, recursively until I know all the objects intersecting with the object that was intersecting with the other and so on.
Example: I am moving object1 and I intersect object2, but object2 intersects object3 that intersects 4, that intersects 5 and so on.
I want to collect all these objects in one array.
What I did was this:
NSMutableArray *intersectingObjects = [NSMutableArray array];
for (Obj *oneObj in allObjects) {
if (oneObj != movingObject) {
if (CGRectIntersectsRect(movingObject.frame, oneObj)) {
[intersectingObjects addObject:oneObj];
}
}
}
// at this point I got an array of all objects intersecting with the
// moving object, then I created a similar block to
// test all these intersecting objects against all objects again,
// then I discovered the objects that were intersecting with the first block
The problem is this just gives me 2 levels deep.
How do I create a recursion here, that will go to the whole tree of possibilities?
thanks.
Because the 1 time calculation would be on the order of O(n^2), I would suggest maintaining an NSMutableArray for each object which contains the objects it is currently intersecting directly. Then the order for each new calculation changes to O(n), simply taking a union of the items in the tree.
However, if you’d still like to pursue the O(n^2) method, here’s an example. I’m assuming Obj is a subclass of UIView?
Then for the driver, just initialize a mutable array and pass in your reference to the original object.