Here is an excerpt from the book Elements of Programming Interviews:
Let P be the set of n points in the plane. Each point has an integer coordinate. Develop an efficient algorithm for computing a string that contains the maximum number of points in P.
As part of the decision, the following is said:
Every pair of distinct points defines a line. We can use a hash table
H to map lines to the set of points in P that lie on them.
And here is the hash function Line:
struct HashLine {
size_t operator()(const Line& l) const {
return hash <int >()(l.slope.first) ^ hash <int >()(l.slope.second) ^ hash <int >()(l.intercept.first) ^ hash <int >()(l.intercept.second);
}
And here is the tilt and intercept announcement:
pair <int, int> get_canonical_fractional(int a, int b) {
int gcd = GCD(abs(a), abs(b));
a /= gcd, b /= gcd;
return b < 0 ? make_pair(-a, -b) : make_pair(a, b);
}
struct Line {
Line(const Point& a, const Point& b)
: slope(a.x != b.x ? get_canonical_fractional(b.y - a.y, b.x - a.x) : make_pair(1, 0))
, intercept(a.x != b.x ? get_canonical_fractional(b.x * a.y - a.x * b.y, b.x - a.x) : make_pair(a.x, 1))
{}
...
pair <int, int> slope;
pair <int, int> intercept;
};
But how do we know that if the slope and intercept pair is unique, then their xor is still unique?
source
share