Search code examples
python-3.xalgorithmzelle-graphics

How to Store a Pair of Points when using Closest Pair Algorithm


I have a closest pair algorithm implemented, I'm attempting to figure out which points in a list of random points of random size are the closest. I'm getting not getting the points in question and I'm either getting it to return the distance again OR just nothing. I'm open to any criticism but I'm confused as to why I'm experiencing these hiccups because in theory when the distance is a new low and the temp indicates this and then I can append or set the pair of points as a variable or within a list.

import math
from math import*
from random import *
from graphics import*

def ClosestPair(P,N):
    #Closest Pair of Points are compared, and the distance between the two pairs
    #is output as a number.
    #
    ret = []
    d = math.inf
    for i in range(N):
        for j in range(i+1,N):
            temp = -1
            d = min(d,sqrt((((P[i].getX() - P[j].getX())**2) + ((P[i].getY() - P[j].getY())**2))))
            if temp < d:
                temp = d
            else:
                ret.append(P[i])
                ret.append(P[j])
    return ret

def main():
    #X&Y is lists that get filled with N values of N size
    #X&Y are appended as the X's and Y's of a Point to Array.
    #Then If ClosestPair = 0 prints closest pair saying points are 
    #overlapping
    #Else prints the Distance and Pair of Points that are Closest
    x = []
    y = []
    array = []

    print('Enter A Size for N')
    n = int(input('N = '))
    for a in range(n):
        x.append(randrange(n))
        y.append(randrange(n))
        array.append(Point(x[a],y[a]))
    #print(array)

    if ClosestPair(array,n) == 0:
        print("The Closest Pair of Points are On top of One another!")
    else:
        print("The Distance between the Closest Points is: ", ClosestPair(array,n), "Points Away")

main()

Solution

  • The inner loop is wrong. It should be something like:

       temp = min(d,sqrt((((P[i].getX() - P[j].getX())**2) + ((P[i].getY() - P[j].getY())**2))))
       if temp < d:
           temp = d
           ret = [P[i], P[j]]
    

    Also your function returns a pair now. Comparing it to 0 makes no sense. Return distance and points if you want or recompute the distance.