I've found a nice code snippet by @belisarius from this question, that I'll reproduce here for reference:
SeedRandom[5];
f := {RandomReal[{0, 10}, 2], RandomReal[{0.05, 3}]}
l = {f};
While[Length@l < 20, While[k = f;
Not[And @@ ((# + k)[[2]] < EuclideanDistance[#[[1]], k[[1]]] & /@
l)]];
AppendTo[l, k]];
Graphics[{Circle @@@ l, FaceForm[Transparent], EdgeForm[Red],
Polygon[{{0, 0}, {0, 10}, {10, 10}, {10, 0}, {0, 0}}]}]

Now, I would like to add two things to it :
All circles (disks) should be randomly colorized (from any color palette),
The parts outside the square should be removed, while leaving the disk's part inside.
Also, I would like a denser generator: all random sized disks should touch its neighbors.
How could we achieve this, using Mathematica version 7.0 ?
Answer
The trick is to place some random non-overlapping Disks in your square area, then use the DistanceTransform to find a point in your square area that is the farthest from its nearest disk. (Such a point will be equidistant from at least two disks--generally three or more disks.) Place a new disk centered at this point, with its radius equal to the distance to its nearest existing disk. Iterate this procedure (here 60 times) using Nest. Then merely plot colored Circles with those centers and radii.
What is nice about this algorithm is that it iteratively finds the largest possible circle consistent with the existing circles, and therefore the radii will never increase during iteration. Note too that it is possible that the algorithm will introduce circles whose centers are on the perimeter of your square area.
startingcenters = {{{5, 8}, 1}, {{1, 6}, 2}, {{9, 8}, .5},
{{8, 2}, .5}, {{1, 1}, 1}};
f[centerset_List] :=
Module[{m = ImageData[
DistanceTransform[
Image[
Graphics[
Disk @@@ centerset,
PlotRange -> {{0, 10}, {0, 10}},
ImageSize -> {1000, 1000}]]]]},
{{#[[2]]/100, 10 - #[[1]]/100}, Max[m]/100} &@ Position[m , Max[m]][[1]]
];
finalcenters = Nest[Union[#, {f[#]}] &, startingcenters, 60];
Graphics[{Hue[RandomReal[]], #} & /@ (Circle @@@ finalcenters),
PlotRange -> {{-0.04, 10.04}, {-0.04, 10.04}},
Epilog -> {Red, Line[{{0, 0}, {0, 10}, {10, 10}, {10, 0}, {0, 0}}]}]

Comments
Post a Comment