Commit 0c108e57 authored by Sadman Kazi's avatar Sadman Kazi 🎸

Solve max points on 2d line

parent 1fcfab1e
#include <vector>
#include <map>
#include <iostream>
#include <algorithm>
#define HASH_LIMIT 100
using namespace std;
struct Point {
int x;
int y;
......@@ -12,42 +10,51 @@ struct Point {
Point(int a, int b) : x(a), y(b) {}
};
using namespace std;
class Solution {
public:
int maxPoints(vector<Point>& points) {
std::map<std::vector<Line>, HASH_LIMIT > map;
static int slope;
static int intercept;
for (int i = 0; i < points.size(); i++) {
for (int j = i+1; j < points.size(); j++) {
slope = calcSlope(points[i], points[j]);
intercept = calcIntercept(points[i], slope);
if (points.size() <= 2) return points.size();
map[key(slope)].push_back(Line(slope, intercept));
std::pair<int, int> slope;
int overlap = 0;
int localmax = 0;
int result = 0;
for (int i = 0; i < points.size() - 1; i++) {
localmax = 0;
overlap = 0;
std::map<std::pair<int, int>, int> lines;
for (int j = i+1; j < points.size(); j++) {
if (points[i].x == points[j].x) {
if (points[i].y == points[j].y) {
// points overlap
overlap++;
continue;
} else {
// else the line is vertical
slope = make_pair(1,0);
}
} else {
slope = makeGCD(points[i].y - points[j].y, points[i].x - points[j].x);
}
lines[slope]++;
localmax = std::max(lines[slope], localmax);
}
result = max(localmax+overlap+1, result);
}
int max = 0;
int cur_max = 0;
for (int i = 0; i < map.size(); i++) {
cur_max = 0;
for (auto iter = map[i].begin(); iter != map[i].end() iter->size() > max; iter++) {
if (iter
}
return 0;
return result;
}
private:
static int key(double slope) {
return (int)slope % HASH_LIMIT;
}
static double calcSlope(const Point& a, const Point& b) {
return (double)(a.y - b.y)/(double)(a.x - b.x);
static std::pair<int, int> makeGCD(int a, int b) {
int g = gcd(a,b);
return make_pair(a/g, b/g);
}
static double calcIntercept(const Point& a, const double& slope) {
return a.y - (a.x * slope);
static int gcd(int a, int b) {
if (b==0) return a;
else return gcd(b, a%b);
}
};
......@@ -56,8 +63,11 @@ int main () {
vector<Point> test = { Point(0,0), Point(1,1), Point(2,2), Point(3,3) };
vector<Point> test2 = {Point(-1,2), Point(3,2), Point(4,4), Point(3,1) };
vector<Point> test3 = {Point(-1,2), Point(-1,2), Point(-1,4), Point(3,2),
Point(3,2), Point(4,4), Point(3,1) };
std::cout << s.maxPoints(test) << std::endl;
std::cout << s.maxPoints(test2) << std::endl;
std::cout << s.maxPoints(test3) << std::endl;
return 0;
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment