#include<iostream>
#include<vector>
#include<math.h>
#include<hash_map>
using namespace std;
class Point{
public:
double x;
double y;
Point() :x(0.0), y(0.0){}
Point(double _x, double _y) :x(_x), y(_y){}
};
class Line{
private:
bool infinite_slope = false;
public:
double epsilon = 0.0001;
double slope;
double intercept;
Line(){}
Line(Point p1, Point p2){
if (fabs(p1.x - p2.x) > epsilon){
slope = (p1.y - p2.y) / (p1.x - p2.x);
intercept = p1.y - slope*p1.x;
}
else{
infinite_slope = true;
intercept = p1.x;
}
}
double floorToNearestEpsilon(double d){
int r = (int)(d / epsilon);
return ((double)r)*epsilon;
}
bool isEquivalent(double a, double b){ return fabs(a - b) < epsilon; }
bool isEquivalent(Line& l){
if (isEquivalent(l.slope, slope) && isEquivalent(l.intercept, intercept) && (infinite_slope == l.infinite_slope))
return true;
return false;
}
};
int countEquivalentLines(vector<Line> lines, Line line){
if (lines.size() == 0) return 0;
int count = 0;
for (int i = 0; i < (int)lines.size(); ++i)
if (lines[i].isEquivalent(line))
++count;
return count;
}
int countEquivalentLines(hash_map<double, vector<Line>> lineBySlope, Line line){
double key = line.floorToNearestEpsilon(line.slope);
int count = countEquivalentLines(lineBySlope[key], line) +
countEquivalentLines(lineBySlope[key - line.epsilon],line) +
countEquivalentLines(lineBySlope[key + line.epsilon],line);
return count;
}
void insertLine(hash_map<double, vector<Line>>& lineBySlope, Line& line){
vector<Line> v;
double key = line.floorToNearestEpsilon(line.slope);
hash_map<double, vector<Line>>::iterator it = lineBySlope.find(key);
if (it == lineBySlope.end()){
lineBySlope[key] = v;
lineBySlope[key].push_back(line);
}
else{
lineBySlope[key].push_back(line);
}
}
Line findBestLine(Point points[],int length){
Line bestLine;
int bestCount = 0;
hash_map<double, vector<Line>> linesBySlope;
for (int i = 0; i < length; ++i){
for (int j = i + 1; j < length; ++j){
Line line(points[i], points[j]);
insertLine(linesBySlope, line);
int count = countEquivalentLines(linesBySlope, line);
if (count > bestCount){
bestLine = line;
bestCount = count;
}
}
}
return bestLine;
}
int main(){
Point p[6] ;
p[0] = Point(1, 1);
p[1] = Point(2, 3);
p[2] = Point(3, 3);
p[3] = Point(4, 5);
p[4] = Point(6, 10);
p[5] = Point(7, 7);
Line l = findBestLine(p,sizeof(p)/sizeof(Point));
cout << std::fixed << l.intercept << " " << l.slope << endl;
cin.get();
return 0;
}
结果显示正确