我正在嘗試生成一組不落在彼此的範圍內的固定區域。我的方法如下:生成點不在對方範圍內?
import collections
from random import uniform
X = 100.0
Y = 100.0
points = 10
radius = 10
def in_circle(c_x, c_y, radius, x, y):
dist_squared = (c_x - x)**2 + (c_y - y)**2
return dist_squared <= radius ** 2
current = collections.defaultdict(lambda: [])
threshold = 0
for point in range(1, points+1):
cX = uniform(1.0, X)
cY = uniform(1.0, Y)
for cur in current:
while in_circle(current[cur][0], current[cur][1], 2*radius, cX, cY):
cX = uniform(1.0, X)
cY = uniform(1.0, X)
threshold += 1
if threshold >= 1e+05:
print "Cannot satisfy constraints"
sys.exit(1)
threshold = 0
current[point] = [cX, cY]
print cX, cY
有沒有一種很好的方法來終止這種算法,而不會進入無限循環?我確實有門檻檢查,但有沒有更好的方法來做到這一點?