Random circles

Random circles

Here’s a macro that fills a part of a picture with more or less evenly and randomly distributed circles that don’t overlap. It takes four arguments: The width and height of the rectangle to be filled, the radius of the circles, and the number of attempts.

For each attempt, a random position is generated. The distances between this position and all existing circles are calculated, and if there’s a collision, no circle is drawn. If the circle does not collide, it is drawn, and its coordinates are added to the list of existing circles.

This approach is far from efficient, but it works.


    \draw (0,0) rectangle (#1,#2);
    \foreach \i in {1,...,#4}{
        \foreach \element [count=\i] in \xlist{
            \pgfmathsetmacro\checkdistance{ sqrt( ({\xlist}[\j]-(\x))^2 + ({\ylist}[\j]-(\y))^2 ) }
            \ifdim\checkdistance pt<\diameter pt
            \draw [red, thick] (\x,\y) circle [radius=#3];




Leave a Reply

Your email address will not be published.