简体   繁体   中英

Find the eculidean distance betweens points in a 2d grid in an optimal way

Given a 2d grid and coordinates of airplanes, find several airplane that are in conflict with each other. An airplane is in conflict with each other if the horizontal distance between airplanes is within 200 meters . Return the total number of airplanes that are in conflict with each other.

Notes : Airplanes is a 2d list => [[1,2], [4,6]] representing x and y coordinates.

I wrote a simple program in python to find the euclidean distance between points of the airplanes:

def find_airplane_conflict(airplanes):
    
    count_conflict = 0

    for i in range (len(airplanes):
        for j in range(len(airplanes):
            if airplanes[i][0] != airplanes[j][0] and airplanes[i][1] != airplanes[j][1]:
                distance = sqrt(pow(airplanes[i][0]-airplanes[j][0],2) + pow(airplanes[i][1]-airplanes[j][1],2) 
                if distance <= 200:
                   count_conflict += 1

   return count_conflict

How can this be optimized from O(N^2) operation without using numpy.

Edit: if the grid is a square area of 10000 and there are 1000 coordinates. I am randomly generating the airplanes coordinates below:

def coordinates():
    return int(random.random() * 10000) 

airplane_coordinates = [[coordinates(), coordinates()] for i in range(1000)]

and passing the coordinates to the function find_airplane_conflict

Take the grid which is of size N*M as described in the code

import random
x_min,x_max=0,10000
y_min,y_max=0,10000
N =(x_max-x_min)//200+1

M =(y_max-y_min)//200+1

grid=[[[] for i in  range(M)] for j in range(N)]

def coordinates():
    return [int(random.random() * 10000),int(random.random() * 10000)] 

airplane_coordinates = [coordinates() for i in range(1000)]

def grid_coordinates(coor):
    return (coor[0]-x_min)//200,(coor[1]-y_min)//200

for i,p in enumerate(airplane_coordinates):
    g_x,g_y=grid_coordinates(p)
    grid[g_x][g_y].append(i)

def find_conflicts():
    counter=0
    for i,p in enumerate(airplane_coordinates):
        g_x,g_y=grid_coordinates(p)
        for i in range(-1,2):
            for j in range(-1,2):
                for index in grid[g_x+i][g_y+j]:
                    counter+=1

    print(counter)
find_conflicts()

Each cell of this grid now contains all the plane indeces which are in the respective 200x200 square. Subsequently you only need to check 9 cells for each plane.

Edit: I rewrote the code now including the real data which is used and corrected some mistakes. Further I also implemented the function which ckhcks all relevant cells. This yields an average number of checks of 5000 instead of 1000000. And it just scales like O(N)

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