clear,clc
axis([0 1 0 1])
rectangle('Position',[0,0,1,.5])
area = zeros(0,1);
totarea = 0;
rectarea = .5;
density = 0;
numballs = 1;
posxtracker = zeros(0,1);
posytracker = zeros(0,1);
radtracker = zeros(0,1);
WRONG = 0;
while totarea == 0
posxrand = randi([0,100],1);
posyrand = randi([0,50],1);
radirand = randi([16,20],1);
posx = posxrand/100;
posy = posyrand/100;
rad = radirand/100;
if ((posx + rad) <= 1.15 && (posx - rad) >= 0 && (posy + rad) <= .5 && (posy - rad) >= 0)
rectangle('Position',[posx-.15,posy,rad,rad],'Curvature',[1,1],'FaceColor', [.7 .7 .7]);
posxtracker(1) = posx;
posytracker(1) = posy;
radtracker(1) = rad;
area(1) = rad*rad*pi;
totarea = totarea + area(1);
else
WRONG = WRONG + 1
end
density = totarea/rectarea;
end
while density < 7.7 && WRONG < 4000
itshouldfit = true;
posxrand = randi([0,100],1);
posyrand = randi([0,50],1);
radirand = randi([16,20],1);
posx = posxrand/100;
posy = posyrand/100;
rad = radirand/100;
i = 1;
while i <= numballs
S = sqrt((posxtracker(i) - posx)^2 + (posytracker(i) - posy)^2);
if S < (radtracker(i)+ rad)
itshouldfit = false;
i = numballs;
end
i = i + 1;
end
if ((posx + rad) <= 1.15 && (posx - rad) >= 0 && (posy + rad) <= .5 && (posy - rad) >= 0 && itshouldfit == true)
rectangle('Position',[posx-.15,posy,rad,rad],'Curvature',[1,1],'FaceColor', [.7 .7 .7]);
numballs = numballs + 1;
posxtracker(numballs) = posx;
posytracker(numballs) = posy;
radtracker(numballs) = rad;
area(numballs) = rad*rad*pi;
totarea = totarea + area(numballs);
else
WRONG = WRONG + 1
end
density = totarea/rectarea;
end
WRONG