Sunday, February 19, 2012

Find a line that intersects max number of points in a plane.


Given a bunch of points, how would you find the line which intersects the most number of points? Write pseudo-code for this algorithm.


Approach:


S = {p1,p2,p3,p4 ..., pn}
Where each point pi = {x, y} coordinates.


for every pair of Pi and Pj calculate:
Equation of line is: y = m*x + b
calculate slope m = (yj-yi)/(xj-xi)
also calculate y intercept b = (yi - m*xi)


Now, have a HashMap with key, value as HashMap H = <slope, <HashMap<y-intercept, count>>
Let G = HashMap<y-intercept, count>;


So for every pair of points we will calculate slope and y-intercept.
First we find if the slope already exists in the hashMap H and then we will check if the y-intercept exists in the 
hash G, if so then increment the counter C.
The Max counter Ci with slope mi and y-intercept bi is the answer.
ie y = mi * x + bi;

No comments:

Post a Comment