sundeepblue
3/12/2014 - 2:26 AM

Given n points on a 2D plane, find the maximum number of points that lie on the same straight line

Given n points on a 2D plane, find the maximum number of points that lie on the same straight line

// can use map data structure to simplify codes

#include <iostream>
#include <vector>
#include <string>
#include <stack>
#include <cmath>
#include <limits>
#include <algorithm>
using namespace std;

struct Point {
      int x, y;
      Point() : x(0), y(0) {}
      Point(int a, int b) : x(a), y(b) {}
};

int maxPoints(vector<Point> &points) {
  if(points.empty()) return 0;
  if(points.size() == 1) return 1;
  int max_num = 0;
  for(int i=0; i<points.size(); i++) {
      Point p1 = points[i];
      unordered_map<double, int> hash;
      int local_dup = 1; // 1 not 0
      for(int j=0; j<points.size(); j++) {
          if(i == j) continue;
          Point p2 = points[j];
          if(p1.x == p2.x && p1.y == p2.y) { // points overlap
              local_dup++;
          } else {
            float slop = get_slop(p1, p2);
            hash[slop]++;
          }
      }
      int max_in_hash = 0;
      for(auto p : hash) 
        max_in_hash = max(max_in_hash, p.second);
      max_num = max(max_num, local_dup + max_in_hash);
      //sort(vslop.begin(), vslop.end());
      //max_num = max(max_num, local_dup + count_max_duplis(vslop));
  }
  return max_num;
}

float get_slop(Point p1, Point p2) {
  if(p1.x == p2.x) return INT_MAX; // wrong if I wrote: return (float)numeric_limits<float>::infinity();
  return (float)(p1.y - p2.y) / (p1.x - p2.x); // forgot float
}

/*
int count_max_duplis(vector<float> v) {
  if(v.empty()) return 0;
  int n = v.size();
  if(n == 1) return 1;
  int max_dup = -1;
  int num = 1;
  for(int i=1; i<n; i++) {
      if(abs(v[i] - v[i-1]) <= 1e-5) num++; // if I wrote 1e-3, not accept!!!
      else {
          max_dup = max(max_dup, num);
          num = 1;
      }
  }
  max_dup = max(max_dup, num); // easy to forgot!
  return max_dup;
} */
    
int main()
{
    vector<Point> vp;
    vp.push_back(Point(4,0));
    vp.push_back(Point(4,-1));
    vp.push_back(Point(4,5));
    cout << maxPoints(vp);
   return 0;
}