Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make for loops run side by side?

Tags:

java

loops

I have been working on a childish little program: there are a bunch of little circles on the screen, of different colors and sizes. When a larger circle encounters a smaller circle it eats the smaller circle, and when a circle has eaten enough other circles it reproduces. It's kind of neat!

However, the way I have it implemented, the process of detecting nearby circles and checking them for edibility is done with a for loop that cycles through the entire living population of circles... which takes longer and longer as the population tends to spike into the 3000 before it starts to drop. The process doesn't slow my computer down, I can go off and play Dawn of War or whatever and there isn't any slow down: it's just the process of checking every circle to see if it has collided with every other circle...

So what occurred to me, is that I could try to separate the application window into four quadrants, and have the circles in the quadrants do their checks simultaneously, since they would have almost no chance of interfering with each other: or something to that effect!

My question, then, is: how does one make for loops that run side by side? In Java, say.

like image 524
Ziggy Avatar asked Nov 29 '22 21:11

Ziggy


1 Answers

the problem you have here can actually be solved without threads.

What you need is a spatial data structure. a quad tree would be best, or if the field in which the spheres move is fixed (i assume it is) you could use a simple grid. Heres the idea.

Divide the display area into a square grid where each cell is at least as big as your biggest circle. for each cell keep a list (linked list is best) of all the circles whose center is in that cell. Then during the collision detection step go through each cell and check each circle in that cell against all the other circles in that cell and the surrounding cells.

technically you don't have to check all the cells around each one as some of them might have already been checked.

you can combine this technique with multithreading techniques to get even better performance.

like image 157
luke Avatar answered Dec 22 '22 00:12

luke