简体   繁体   English

从N个2D点返回成对的点,其中每两个点定义一条线

[英]Return pairs of points from N 2D points where each two points define a line

I have a List of 2D points: (x1, y1), (x2, y2) … (xN, yN) - N 2D points. 我有一个2D点列表:(x1,y1),(x2,y2)…(xN,yN)-N 2D点。 Each two points define a 2D line. 每两个点定义一条2D线。

Return a list of all unique 2D lines, which you can build using pairs of points from the list. 返回所有唯一2D线的列表,您可以使用列表中的成对点进行构建。

How can I implement using hash table/map - to keep unique lines (there are infinite lines) 我如何实现使用哈希表/映射-保持唯一的行(有无限的行)

I am trying to find the slope and intercept then point of intersection. 我正在尝试查找坡度并拦截然后相交的点。

slope = y2 -y1 / x2 - x1 intercept = y1 - slope * x1; 斜率= y2 -y1 / x2-x1截距= y1-斜率* x1;

(trying to do this in c++) (尝试在C ++中执行此操作)

you didn't specify language, so I will use python here for the sake of easiness. 您没有指定语言,因此为了简便起见,我将在此处使用python。 it will look like a joke to python: 看起来像是对Python的玩笑:

import itertools


def slope(p1, p2):
    return (p1[1]-p2[1]) / (p1[0]-p2[0])


def slp_intrcpt(p1, p2):
    """
    return the tuple of slope and intercept
    """
    slp = slope(p1, p2)
    return slp, p1[1] - slp * p1[0]


def uniq_lines(points):
    return set(slp_intrcpt(p1, p2) for p1, p2 in itertools.combinations(points, 2))

since (slope, intercept) pair is good enough to determine a line, so i would say that finished your requirement. 由于(slope, intercept)对足以确定一条线,所以我想说完了您的要求。

if you want to keep track of all pairs that produce the lines, you may 如果您想跟踪所有产生线的对,则可以

import collections

def uniq_lines(points):
    d = collections.defaultdict(lambda: [])
    for p1, p2 in itertools.combinations(points, 2):
        d[slp_intrcpt(p1, p2)].append((p1, p2))
    return d

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM