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!
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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With