Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: randomly generating circles that do not intersect (stuck in while loop)

Tags:

java

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

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

Over here, I generate a random x and y position (inside the canvas of xSize by ySize) for every RBC (a total of amountRBC, for demonstration purposes, let's say 5). These x and y positions get stored in the array xPosRBC[] and yPosRBC[] 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 for every point whether they are less than 2*radius of the circle apart (using this sqrt((|xpos1-xpos2|)^2+(|ypos1-ypos2|)^2) formula) and if they are, a new position is generated and the "checking" for-loop gets reset (j=0). Repeat this process for every circle there is (from i=0 to amountRBC). In my reasoning this should end up with 5 random placed circles, which all have a distance of at least 2*radius apart, which means they should not intersect. However, the program seems to get stuck in this while-loop indefinitely and I can't seem to find out why.

[NOTE]: there are only a small amount of circles, with a small radius on a large canvas. This means that the case that there isn't enough screen to fill up the circles cannot be the problem.

Any help would be greatly appreciated!

like image 754
ItsTheSebbe Avatar asked Feb 15 '26 04:02

ItsTheSebbe


2 Answers

I have just found out the solution to the problem. Namely, in said while loop, it also compared the size of the circle to its own position, so that distance will always be 0. In the while loop I've added the operant (&& i!=j) and now it seems to be working fine. Thanks guys!

like image 89
ItsTheSebbe Avatar answered Feb 16 '26 17:02

ItsTheSebbe


I think you need to execute the inner loop as follows:

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

As it stands when j is equal to i it will find that circle intersects itself, regenerate and reset j.

like image 31
Persixty Avatar answered Feb 16 '26 17:02

Persixty