I’m programming physics for a small 2D game, and I need to check every object on the screen against every other object on the screen. That’s O(N^2), and I don’t really like that.
What I had in mind:
for (var i = 0; i < objects.length; i ++)
for (var j = 0; j < objects.length; j ++)
if (collide(objects[i], objects[j])) doStuff(objects[i], objects[j]);
This is unnecessary, and I will check the same objects against one another multiple times. How can I avoid that? I thought of having a matrix, which would be n*n (given that n is the number of objects), and then each time I visit a pair of objects I would to this:
visited[i][j] = 1;
visited[j][i] = 1;
And then, I would always know which pair of objects I visited.
This would work, however, I would, again, need to set all of those cells, n*n times, just to set them all to 0 at start! Maybe, I could set everything to [], but this still doesn’t seem like a viable solution to me. Is there something better?
Obviously, my language of choice is Javascript, but I know C, C++ and Python relatively fluently, so you can answer in them (although Javascript, C and C++ have almost the same syntax).
You won’t avoid O(n^2), but you can cut it down by half:
Assuming collision is symmetric. If it’s also reflexive, and testing for collision is expensive, you can move
doStuff(object[i], object[i])out of the inner loop to avoid testing for collision and start the inner loop fromi+1