python - 如何检查 2D 图形中的所有点的距离并确保没有一个点太近?
问题描述
我想创建并返回一组随机的 2 元素元组,它们表示 2D 图上的点。我的问题是我希望每个点彼此之间至少有一定的距离。这应该根据下面函数中 minDistance 参数的值。
我想不出一种方法来遍历一组并检查每个点的距离,同时替换距离不够远的点。我怎样才能做到这一点?
注意:该图的长度为 90 点,宽度为 160 点。
到目前为止,这是我的功能:
def makeTiles(num, xBounds, yBounds, minDistance):
"""
Creates and returns a set of points.
:param num: int
The number of points to be returned.
:param xBounds: tuple of 2 ints
The first element is the minimum an x-value should be.
The second element is the maximum an x-value should be.
:param yBounds: tuple of 2 ints
The first element is the minimum an y-value should be.
The second element is the maximum an y-value should be.
:param minDistance: int
The minimum distance that should occur between points.
:return: set of tuples
The set of points that will be created.
"""
tileSet = set()
for n in range(num):
x = r.randint(xBounds[0], xBounds[1])
y = r.randint(yBounds[0], yBounds[1])
tileSet.add((x, y))
tempSet = tileSet.copy()
distances = set()
for t1 in tempSet:
for t2 in tileSet:
distances.add(m.sqrt((t1[0] - t2[0]) ** 2 + (t1[1] - t2[1]) ** 2))
for d in distances:
if d < minDistance:
解决方案
您应该研究Quadtrees,它们可以在这种检查中提供更好的性能。除此之外,除了检查图表中每个点到每个其他点的距离外,别无他法。
还要确保在比较点时,不要对照自身检查点。
推荐阅读
- css - 如何在 Angular Material Design 中为嵌套元素添加 CSS
- r - Ggplot2 计算时间段
- python - 如何使用 Python 执行终端命令
- python - Pinecsript 到 Python 的转换
- r - 如何将月份和日期没有前导零的字符转换为日期?
- python - 使用 Python 从 BAM 文件和 vcf 文件中提取具有不同位置的读取和配对(PYSAM 和 PYSAM,也可以使用 bamnostics)
- c - C递归函数不可能?
- java - 如何将动作侦听器添加到静态 Jbutton?
- json - 试图将 GSON 中的 String jSON 数据解析为具有 String 值的枚举类。收到 BEGIN_OBJECT 而不是 String 的错误
- math - 您如何找到二维中两个三角形之间的交点/重叠的中心点?