Shortest distance between points algorithm

前端 未结 7 2027
独厮守ぢ
独厮守ぢ 2020-11-29 03:47

Given a set of points on a plane, find the shortest line segment formed by any two of these points.

How can I do that? The trivial way is obviously to calcu

相关标签:
7条回答
  • 2020-11-29 04:23

    From your question it is not clear if you are looking for the distance of the segment, or the segment itself. Assuming you are looking for the distance (the segment in then a simple modification, once you know which are the two points whose distance is minimal), given 5 points, numbered from 1 to 5, you need to

    compare 1 with 2,3,4,5, then 
    compare 2, with 3,4,5, then 
    compare 3 with 4,5, then 
    compare 4 with 5.
    

    If I am not wrong, given the commutativity of the distance you do not need to perform other comparisons. In python, may sound like something

    import numpy as np
    def find_min_distance_of_a_cloud(cloud):
            """
            Given a cloud of points in the n-dim space, provides the minimal distance.
            :param cloud: list of nX1-d vectors, as ndarray.
            :return:
            """
            dist_min = None
            for i, p_i in enumerate(cloud[:-1]):
                new_dist_min = np.min([np.linalg.norm(p_i - p_j) for p_j in cloud[(i + 1):]])
                if dist_min is None or dist_min > new_dist_min:
                    dist_min = new_dist_min
    
            return dist_min
    

    That can be tested with something like the following code:

    from nose.tools import assert_equal
    
    def test_find_min_distance_of_a_cloud_1pt():
        cloud = [np.array((1, 1, 1)), np.array((0, 0, 0))]
        min_out = find_min_distance_of_a_cloud(cloud)
        assert_equal(min_out, np.sqrt(3))
    
    
    def test_find_min_distance_of_a_cloud_5pt():
        cloud = [np.array((0, 0, 0)),
                 np.array((1, 1, 0)),
                 np.array((2, 1, 4)),
                 np.array((3, 4, 4)),
                 np.array((5, 3, 4))]
        min_out = find_min_distance_of_a_cloud(cloud)
        assert_equal(min_out, np.sqrt(2))
    

    If more than two points can have the same minimal distance, and you are looking for the segments, you need again to modify the proposed code, and the output will be the list of points whose distance is minimal (or couple of points). Hope it helps!

    0 讨论(0)
提交回复
热议问题