2

I am trying to generate model of randomly distributed uniform spheres in the cube. For randomly distributed spheres I am using RandomReal option. But when I run the program I obtain a cube with several spheres located either inside each other or have intersections. Is there any way to make them apart and non-intersecting?

Here is a code of this problem:

cube = {Opacity[0.3], Cuboid[{0, 0, 0}, {20, 20, 20}]};
spheres = Table[{Green, Sphere[RandomReal[{1, 20-1}, 3], 1]}, {j, 1, 100}];
gr = Graphics3D[{cube, spheres}]

Mathematica graphics

Öskå
  • 8,587
  • 4
  • 30
  • 49
Bakha
  • 39
  • 3

1 Answers1

3

Keep a list of the locations you add - draw from a uniform distribution and only add to the list if it doesn't overlap.

cube = {Opacity[0.3], Cuboid[{0, 0, 0}, {20, 20, 20}]};

newLocation[existing_]:= Module[{try,count=1},
  While[
    try=RandomReal[{1,19},3];
    Min[EuclideanDistance[try,#[[1]]]&/@existing]<2,
    count++
  ];
  {try,count}
]

makeLocations[n_]:=Module[{list={},loc},
  Do[
    loc=newLocation[list];
    AppendTo[list,loc],
    {n}
  ];
  list
]

spheres={Green,Sphere[#[[1]],1]&/@makeLocations[100]};

gr = Graphics3D[{cube, spheres}]
SEngstrom
  • 1,711
  • 12
  • 14