简体   繁体   中英

How to eficiently find the closest point from a distinct set of points to each point of another set in python

I have this code

import random as rand


W = 2
H = 2
n_riders = 10
n_drivers = 20
riders_coords = []
drivers_coords = []
for n in range(n_riders):
    x = rand.uniform(-1,1)*W
    y = rand.uniform(-1,1)*H
    riders_coords.append((x, y))
for n in range(n_drivers):
    x = rand.uniform(-1,1)*W
    y = rand.uniform(-1,1)*H
    drivers_coords.append((x, y))
print(riders_coords)
print(drivers_coords)

I would like to find a way to pair each rider to the closest driver (euclidian distance) taking into account that a single driver can only be assigned to a single rider. The objective is to find the parings that minimizes the total distance. All riders should be assigned to a driver if n_riders <= n_drivers. Does anyone know a simple way to achieve that or do I have to start drawing voronoi polygons from scratch?

Your problem is known as the Euclidean assignment problem , or alternatively the Euclidean bipartite matching problem . The problem has been studied academically, and there are some known algorithms, but I didn't find any information about them except in academic papers:

  • Vaidya (1989) described an algorithm which runs in O(n^2.5 log n) time.
  • Agarwal, Efrat & Sharir (1999) described one which runs in O(n^(2 + ε)) time for arbitrarily small ε .
  • Agarwal & Varadarajan (2004) described a heuristic algorithm which runs in O(n^(1 + ε)) time and finds a matching with expected weight within a constant factor of the true minimum.

You can probably find a few more published algorithms or heuristics by searching the literature.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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