Line Findbestline (graphpoint[] points)
{
Line Bestline =null;
int bestcount=0;
Hashmap<double,arraylist<line>> linesbyslope=
New Hashmap<double,arraylist<line>> ();
for (int i=0;i<points.length;i++)
{
for (int j=i+1;j<points.length;j++)
{
Line Line=new Line (Points[i],points[j]);
Insertline (Linesbyslope,line);
int Count=countequivalentlines (linesbyslope,line);
if (Count>bestcount)
{
Bestline=line;
Bestcount=count;
}
}
}
return bestline;
}
int Countequivallines (hashmap<double,arraylist<line>> linesbyslope,line line)
{
Double Key=line.floortonearestepsilon (Line.slope);
Double Eps=line.epsilon;
int Count=countequivalentlines (Linesbyslope.get (key), line) +countequivalentlines (Linesbyslope.get (key-eps), line) +countequivalentlines (Linesbyslope.get (key+eps), line);
return count;
}
void Insertline (hashmap<double,arraylist<line>> liensbyslope,line line)
{
Arraylist<line> Lines=null;
Double Key=line.floortonearestepsilon (Line.slope);
if (!linesbyslope.containskey (key))
{
Lines=new arraylist<line> ();
Linesbyslope.put (Key,lines);
}
Else
{
Lines=linesbyslope.get (key);
}
Lines.add (line);
}
public class Line
{
public static double epsilon=.0001;
public double slope,intercept;
Private Boolean infinite_slope=false;
Public line (Graphpoint p,graphpoint q)
{
if (Math.Abs (p.x-q.x) >epsilon)
{
Slope= (P.Y-Q.Y)/(p.x-q.x);//Slope
intercept=p.y-slope*p.x;//using y=mx+b to calculate y-axis intercept
}
Else
{
Infinite_slope=true;
intercept=p.x;//x axis Intercept. Because the slope infinity
}
}
public static double Floortonearestepsilon (double D)
{
int r= (int) (D/epsilon);
Return (double) r) *epsilon;
}
public boolean isequivalent (double a,double b)
{
Return (Math.Abs (A-B) <epsilon);
}
public boolean isequivalent (Object o)
{
Line l= o;
if (Isequivalent (l.slope,slope) && isequivalent (l.intercept,intercept) && (infinitte_slope== L.infinite_slope))
{
return true;
}
return false;
}
}
It is important to be cautious in calculating the slope of a straight line, which is likely to be completely perpendicular, i.e. it has no y intercept and is infinitely large. A separate tag (infinite_slope) can be used to track records. In the Equals method, this condition must be checked.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
On the two-dimensional plane, there are some points. Please find the line that passes the most points