0

I have the following problem.

Given an array of 2*N elements, the first and second halves are x and y coordinates.

I want to calculate the smallest distance between those points.

As example:

sol = [0.37454012, 0.95071431, 0.73199394, 0.59865848, 0.15601864,
       0.15599452, 0.05808361, 0.86617615, 0.60111501, 0.70807258]

The respective points are:

[(0.3745401188473625, 0.15599452033620265),
 (0.9507143064099162, 0.05808361216819946),
 (0.7319939418114051, 0.8661761457749352),
 (0.5986584841970366, 0.6011150117432088),
 (0.15601864044243652, 0.7080725777960455)]

The smallest distance is equal to 0.29670818834575136

Right now I solve with this code bellow:

import numpy as np
from scipy.spatial.distance import cdist
np.random.seed(42)
sol = np.random.rand(10)

x = sol[:len(sol)//2]
y = sol[len(sol)//2:]

points = list(zip(x,y))

m = cdist(points, points, 'euclidean')
m = m + np.where(np.eye(m.shape[0])>0,np.inf,0)

smallest = m.min()

Is there any faster way to do this? That's the objective function inside an heuristic and it is calculated thousands of times.

seimetz
  • 171
  • 7
  • @Prune The answer provided at https://stackoverflow.com/questions/35806681/euclidean-distance-between-all-points-in-an-2-vectors does not solve the problem for me. if I use that method with the same data, it gives me a different answer – seimetz May 23 '20 at 22:05
  • What I am asking here is about 2-dimensional arrays. That's why the only way I figured out was to use scipy.distance.cdist – seimetz May 23 '20 at 22:12
  • 1
    This closure is incorrect. The poster asks for the *minimum* distance between pairs of points but the linked to question is about finding distances between *all* pairs of points. – Björn Lindqvist May 23 '20 at 22:28
  • The linked duplicate is the fastest way to determine all distances, from which one merely extracts the minimum value. – Prune May 23 '20 at 22:50
  • The algorithmic problem is not a matter of working with a 2D array -- that's an implementation detail, no? YOu have a 1D array of *points*, and you need to find the minimum of the `N*(N-1)/2` Euclidean distances. Have I misunderstood the problem? – Prune May 23 '20 at 22:51
  • 1
    I think you have, see the [Closest pair of points problem](https://en.wikipedia.org/wiki/Closest_pair_of_points_problem). First computing all pairwise distances and then finding the minimum is O(n^2) but there are standard algorithms for doing it in O(n*log(n)) time in 2d space. – Björn Lindqvist May 23 '20 at 23:31
  • Never heard about this problem, but it is exactly what I'm looking for! thanks @BjörnLindqvist. An O(n*log(n)) method will probably improve a lot the whole algorithm – seimetz May 24 '20 at 22:03
  • See this question: https://stackoverflow.com/questions/1602164/shortest-distance-between-points-algorithm It appears to be fairly close to what you want. – Björn Lindqvist May 24 '20 at 23:19

0 Answers0