Java: randomly generating circles that do not intersect (get stuck during loop)

I want to create random circles on a constrained canvas. Namely, none of the circles should intersect. I have come up with a check so far to see if the circles intersect, and if they do, it generates a new one. Here's my reasoning along with the code:

for(int i=0;i<amountRBC;i++)
        {
            xPosRBC[i]=random.nextInt(xSize);
            yPosRBC[i]=random.nextInt(ySize);
        }

      

Here I am generating a random x and y position (inside the canvas xSize by ySize) for each RBC (total amountRBC for demo purposes, say 5). These x and y positions are stored in the xPosRBC [] and yPosRBC [] arrays, respectively.

for(int i=0;i<amountRBC;i++)
        {
            for(int j=0;j<amountRBC;j++)
            {
                while(Math.sqrt(Math.pow(Math.abs(xPosRBC[j]-xPosRBC[i]),2)+Math.pow(Math.abs(yPosRBC[j]-yPosRBC[i]), 2))<(2*rbcRadius))
                {
                    xPosRBC[i]=random.nextInt(xSize); //random starting position of bacterium
                    yPosRBC[i]=random.nextInt(ySize);
                    j=0;
                }
            }
        }

      

then I check each point, no matter if they are the radius of the circle radius 2 (using this formula sqrt ((| xpos1-xpos2 |) ^ 2 + (| ypos1-ypos2 |) ^ 2)) and if they create a new position and "check" for the loop gets reset (j = 0). Repeat this process for each lap (i = 0 to RBC sum). By my reasoning this should consist of 5 randomly placed circles, each with a distance of at least 2 * radius, which means they should not intersect. However, the program seems to be stuck in this while-loop indefinitely and I cannot figure out why.

[NOTE]: just a small number of small radius circles on a large canvas. This means that the problem that the screen is not enough to fill the circles cannot be the problem.

Any help would be greatly appreciated!

+3


source to share


3 answers


I just found a solution to the problem. Namely, in the said while loop, it also compared the size of the circle to its own position, so that the distance is always 0. In the while loop, I added an operand (& & i! = J) and now it works fine. Thanks guys!



+2


source


I think you need to execute the inner loop like this:

for(int j=0;j<amountRBC;j++) {
    if(j==i){
        continue;
    }

      



In the event that it j

is equal i

, it will find that the circle intersects itself, regenerate and reset j

.

+2


source


I don't think you are stuck with a while loop, but the for loop, since you reset the internal loop counter j=0;

inside the while loop, it will never exit.

Confirm this with some printouts and you will see where you are stuck. Also helps to print (or debug) to see which condition is not what is expected and what content it belongs to.

0


source







All Articles