此代码生成 10 个半径为 10 且彼此不相交的圆。我同意 bames53 的观点,即最好的方法是检查生成的圆是否与先前生成的圆相交。
// Seed random generator
srand(time(NULL));
const float radius = 10;
const int numberOfCircles = 10;
// Defines the area where the center of the circles are allowed
const float min_x = 0 + radius;
const float max_x = 320 - radius;
const float min_y = 0 + radius;
const float max_y = 367 - radius;
NSMutableSet * nonInterSectingCircles = [NSMutableSet setWithCapacity:numberOfCircles];
while ([nonInterSectingCircles count] < numberOfCircles ) {
float x_new = randomNumber(min_x, max_x);
float y_new = randomNumber(min_y, max_y);
BOOL intersectsExistingCircle = NO;
for (NSValue *center in nonInterSectingCircles) {
CGPoint centerPoint = [center CGPointValue];
if (distance(x_new, centerPoint.x, y_new, centerPoint.y) < radius * 2)
intersectsExistingCircle = YES;
}
if (!intersectsExistingCircle) [nonInterSectingCircles addObject:[NSValue valueWithCGPoint:CGPointMake(x_new, y_new)]];
}
使用以下函数:
float distance(float x1,float x2, float y1, float y2) {
float dx = (x2 - x1);
float dy = (y2 - y1);
return sqrt(dx * dx + dy * dy);
}
float randomNumber(float min, float max) {
float random = ((float) rand()) / (float) RAND_MAX;
random = random * (max - min);
return min + random;
}