0% found this document useful (0 votes)
73 views15 pages

Length of Union of Segments of A Line: Lines

The document discusses several algorithms related to geometry problems: 1. It provides a C++ program to check if two line segments intersect by calculating the orientation of points and checking for special cases like collinear points. 2. It discusses calculating the length of the union of multiple line segments by sorting the starting and ending points and adding differences between adjacent points. 3. It describes a method to find the maximum number of points lying on the same line by calculating slopes of line segments and storing frequencies in a hash map. 4. An algorithm is presented to determine the minimum number of lines needed to cover all given points where all lines pass through a fixed point by storing slopes in a set. 5

Uploaded by

Yassir Hasker
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
73 views15 pages

Length of Union of Segments of A Line: Lines

The document discusses several algorithms related to geometry problems: 1. It provides a C++ program to check if two line segments intersect by calculating the orientation of points and checking for special cases like collinear points. 2. It discusses calculating the length of the union of multiple line segments by sorting the starting and ending points and adding differences between adjacent points. 3. It describes a method to find the maximum number of points lying on the same line by calculating slopes of line segments and storing frequencies in a hash map. 4. An algorithm is presented to determine the minimum number of lines needed to cover all given points where all lines pass through a fixed point by storing slopes in a set. 5

Uploaded by

Yassir Hasker
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

Lines :

How to check if two given line segments intersect?


Length Of Union Of Segments of a line
Count maximum points on same line
Minimum lines to cover all points
Minimum block jumps to reach destination

Triangle :
Check whether a given point lies inside a triangle or not
Rectangle | Square | Circle :
Pizza cut problem (Or Circle Division by Lines)
Maximum points that can be enclosed in a circle of
given radius
Check if a line touches or intersects a circle
Check whether given circle resides in boundary
maintained by two other circles
Minimum circle problem
How to check if two given line segments intersect?
// A C++ program to check if two given line segments intersect
#include <iostream>
using namespace std;

struct Point
{
int x;
int y;
};

// Given three colinear points p, q, r, the function checks if


// point q lies on line segment 'pr'
bool onSegment(Point p, Point q, Point r)
{
if (q.x <= max(p.x, r.x) && q.x >= min(p.x, r.x) &&
q.y <= max(p.y, r.y) && q.y >= min(p.y, r.y))
return true;

return false;
}

// To find orientation of ordered triplet (p, q, r).


// The function returns following values
// 0 --> p, q and r are colinear
// 1 --> Clockwise
// 2 --> Counterclockwise
int orientation(Point p, Point q, Point r)
{
// See https://www.geeksforgeeks.org/orientation-3-ordered-points/
// for details of below formula.
int val = (q.y - p.y) * (r.x - q.x) -
(q.x - p.x) * (r.y - q.y);

if (val == 0) return 0; // colinear

return (val > 0)? 1: 2; // clock or counterclock wise


}

// The main function that returns true if line segment 'p1q1'


// and 'p2q2' intersect.
bool doIntersect(Point p1, Point q1, Point p2, Point q2)
{
// Find the four orientations needed for general and
// special cases
int o1 = orientation(p1, q1, p2);
int o2 = orientation(p1, q1, q2);
int o3 = orientation(p2, q2, p1);
int o4 = orientation(p2, q2, q1);

// General case
if (o1 != o2 && o3 != o4)
return true;

// Special Cases
// p1, q1 and p2 are colinear and p2 lies on segment p1q1
if (o1 == 0 && onSegment(p1, p2, q1)) return true;

// p1, q1 and q2 are colinear and q2 lies on segment p1q1


if (o2 == 0 && onSegment(p1, q2, q1)) return true;
// p2, q2 and p1 are colinear and p1 lies on segment p2q2
if (o3 == 0 && onSegment(p2, p1, q2)) return true;

// p2, q2 and q1 are colinear and q1 lies on segment p2q2


if (o4 == 0 && onSegment(p2, q1, q2)) return true;

return false; // Doesn't fall in any of the above cases


}

// Driver program to test above functions


int main()
{
struct Point p1 = {1, 1}, q1 = {10, 1};
struct Point p2 = {1, 2}, q2 = {10, 2};

doIntersect(p1, q1, p2, q2)? cout << "Yes\n": cout << "No\n";

p1 = {10, 0}, q1 = {0, 10};


p2 = {0, 0}, q2 = {10, 10};
doIntersect(p1, q1, p2, q2)? cout << "Yes\n": cout << "No\n";

p1 = {-5, -5}, q1 = {0, 0};


p2 = {1, 1}, q2 = {10, 10};
doIntersect(p1, q1, p2, q2)? cout << "Yes\n": cout << "No\n";

return 0;
}

Length Of Union Of Segments of a line


#include<bits/stdc++.h>
using namespace std;

// Returns sum of lengths covered by union of given


// segments
int segmentUnionLength(const vector <pair <int,int> > &seg)
{
int n = seg.size();

// Create a vector to store starting and ending


// points
vector <pair <int, bool> > points(n * 2);
for (int i = 0; i < n; i++)
{
points[i*2] = make_pair(seg[i].first, false);
points[i*2 + 1] = make_pair(seg[i].second, true);
}

// Sorting all points by point value


sort(points.begin(), points.end());

int result = 0; // Initialize result

// To keep track of counts of current open segments


// (Starting point is processed, but ending point
// is not)
int Counter = 0;

// Trvaerse through all points


for (unsigned i=0; i<n*2; i++)
{
// If there are open points, then we add the
// difference between previous and current point.
// This is interesting as we don't check whether
// current point is opening or closing,
if (Counter)
result += (points[i].first - points[i-1].first);

// If this is an ending point, reduce, count of


// open points.
(points[i].second)? Counter-- : Counter++;
}
return result;
}

// Driver program for the above code


int main()
{
vector< pair <int,int> > segments;
segments.push_back(make_pair(3, 15));
segments.push_back(make_pair(2, 5));
segments.push_back(make_pair(4, 8));
segments.push_back(make_pair(9, 12));
cout << "Length of Union of All segments = ";
cout << segmentUnionLength(segments) << endl;
return 0;
}

Count maximum points on same line


#include <bits/stdc++.h>
#include <boost/functional/hash.hpp>

using namespace std;

// method to find maximum colinear point


int maxPointOnSameLine(vector< pair<int, int> > points)
{
int N = points.size();
if (N < 2)
return N;

int maxPoint = 0;
int curMax, overlapPoints, verticalPoints;

// here since we are using unordered_map


// which is based on hash function
//But by default we don't have hash function for pairs
//so we'll use hash function defined in Boost library
unordered_map<pair<int, int>, int,boost::
hash<pair<int, int> > > slopeMap;

// looping for each point


for (int i = 0; i < N; i++)
{
curMax = overlapPoints = verticalPoints = 0;

// looping from i + 1 to ignore same pair again


for (int j = i + 1; j < N; j++)
{
// If both point are equal then just
// increase overlapPoint count
if (points[i] == points[j])
overlapPoints++;

// If x co-ordinate is same, then both


// point are vertical to each other
else if (points[i].first == points[j].first)
verticalPoints++;

else
{
int yDif = points[j].second - points[i].second;
int xDif = points[j].first - points[i].first;
int g = __gcd(xDif, yDif);

// reducing the difference by their gcd


yDif /= g;
xDif /= g;

// increasing the frequency of current slope


// in map
slopeMap[make_pair(yDif, xDif)]++;
curMax = max(curMax, slopeMap[make_pair(yDif, xDif)]);
}

curMax = max(curMax, verticalPoints);


}

// updating global maximum by current point's maximum


maxPoint = max(maxPoint, curMax + overlapPoints + 1);

// printf("maximum colinear point


// which contains current point
// are : %d\n", curMax + overlapPoints + 1);
slopeMap.clear();
}

return maxPoint;
}

// Driver code
int main()
{
const int N = 6;
int arr[N][2] = {{-1, 1}, {0, 0}, {1, 1}, {2, 2},
{3, 3}, {3, 4}};

vector< pair<int, int> > points;


for (int i = 0; i < N; i++)
points.push_back(make_pair(arr[i][0], arr[i][1]));

cout << maxPointOnSameLine(points) << endl;

return 0;
}

Minimum lines to cover all points


#include <bits/stdc++.h>
using namespace std;

// Utility method to get gcd of a and b


int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}

// method returns reduced form of dy/dx as a pair


pair<int, int> getReducedForm(int dy, int dx)
{
int g = gcd(abs(dy), abs(dx));

// get sign of result


bool sign = (dy < 0) ^ (dx < 0);

if (sign)
return make_pair(-abs(dy) / g, abs(dx) / g);
else
return make_pair(abs(dy) / g, abs(dx) / g);
}

/* method returns minimum number of lines to


cover all points where all lines goes
through (xO, yO) */
int minLinesToCoverPoints(int points[][2], int N,
int xO, int yO)
{
// set to store slope as a pair
set< pair<int, int> > st;
pair<int, int> temp;
int minLines = 0;

// loop over all points once


for (int i = 0; i < N; i++)
{
// get x and y co-ordinate of current point
int curX = points[i][0];
int curY = points[i][1];

temp = getReducedForm(curY - yO, curX - xO);

// if this slope is not there in set,


// increase ans by 1 and insert in set
if (st.find(temp) == st.end())
{
st.insert(temp);
minLines++;
}
}

return minLines;
}

// Driver code to test above methods


int main()
{
int xO, yO;
xO = 1;
yO = 0;
int points[][2] =
{
{-1, 3},
{4, 3},
{2, 1},
{-1, -2},
{3, -3}
};

int N = sizeof(points) / sizeof(points[0]);


cout << minLinesToCoverPoints(points, N, xO, yO);
return 0;
}

Minimum block jumps to reach destination


#include <bits/stdc++.h>
using namespace std;

// To represent point in 2D space


struct point
{
int x, y;
point(int x, int y) : x(x), y(y)
{}
};

// To represent line of (ax + by + c)format


struct line
{
int a, b, c;
line(int a, int b, int c) : a(a), b(b), c(c)
{}
line()
{}
};

// Returns 1 if evaluation is greater > 0,


// else returns -1
int evalPointOnLine(point p, line curLine)
{
int eval = curLine.a* p.x +
curLine.b * p.y +
curLine.c;
if (eval > 0)
return 1;
return -1;
}

// Returns minimum jumps to reach


// dest point from start point
int minJumpToReachDestination(point start,
point dest, line lines[], int N)
{
int jumps = 0;
for (int i = 0; i < N; i++)
{
// get sign of evaluation from point
// co-ordinate and line equation
int signStart = evalPointOnLine(start, lines[i]);
int signDest = evalPointOnLine(dest, lines[i]);

// if both evaluation are of opposite sign,


// increase jump by 1
if (signStart * signDest < 0)
jumps++;
}

return jumps;
}

// Driver code to test above methods


int main()
{
point start(1, 1);
point dest(-2, -1);

line lines[3];
lines[0] = line(1, 0, 0);
lines[1] = line(0, 1, 0);
lines[2] = line(1, 1, -2);

cout << minJumpToReachDestination(start, dest, lines, 3);

return 0;
}

Check whether a given point lies inside a triangle or not


#include <bits/stdc++.h>
using namespace std;

/* A utility function to calculate area of triangle formed by (x1, y1),


(x2, y2) and (x3, y3) */
float area(int x1, int y1, int x2, int y2, int x3, int y3)
{
return abs((x1*(y2-y3) + x2*(y3-y1)+ x3*(y1-y2))/2.0);
}

/* A function to check whether point P(x, y) lies inside the triangle formed
by A(x1, y1), B(x2, y2) and C(x3, y3) */
bool isInside(int x1, int y1, int x2, int y2, int x3, int y3, int x, int y)
{
/* Calculate area of triangle ABC */
float A = area (x1, y1, x2, y2, x3, y3);

/* Calculate area of triangle PBC */


float A1 = area (x, y, x2, y2, x3, y3);

/* Calculate area of triangle PAC */


float A2 = area (x1, y1, x, y, x3, y3);

/* Calculate area of triangle PAB */


float A3 = area (x1, y1, x2, y2, x, y);

/* Check if sum of A1, A2 and A3 is same as A */


return (A == A1 + A2 + A3);
}
/* Driver program to test above function */
int main()
{
/* Let us check whether the point P(10, 15) lies inside the triangle
formed by A(0, 0), B(20, 0) and C(10, 30) */
if (isInside(0, 0, 20, 0, 10, 30, 10, 15))
printf ("Inside");
else
printf ("Not Inside");

return 0;
}

Pizza cut problem (Or Circle Division by Lines)


// C++ program to find maximum no of pieces
// by given number of cuts
#include<bits/stdc++.h>
using namespace std;

// Function for finding maximum pieces


// with n cuts.
int findMaximumPieces(int n)
{
return 1 + n*(n+1)/2;
}

// Driver code
int main()
{
cout << findMaximumPieces(3);
return 0;
}

Maximum points that can be enclosed in a circle of given


radius
#include <bits/stdc++.h>
using namespace std;

const int MAX_POINTS = 500;

// complex class which is available in STL has


// been used to implement points. This helps to
// ensure greater functionality easily
typedef complex<double> Point;

Point arr[MAX_POINTS];
double dis[MAX_POINTS][MAX_POINTS];

// This function returns the maximum points that


// can lie inside the circle of radius 'r' being
// rotated about point 'i'
int getPointsInside(int i, double r, int n)
{
// This vector stores alpha and beta and flag
// is marked true for alpha and false for beta
vector<pair<double, bool> > angles;

for (int j=0; j<n; j++)


{
if (i != j && dis[i][j] <= 2*r)
{
// acos returns the arc cosine of the complex
// used for cosine inverse
double B = acos(dis[i][j]/(2*r));

// arg returns the phase angle of the complex


double A = arg(arr[j]-arr[i]);
double alpha = A-B;
double beta = A+B;
angles.push_back(make_pair(alpha, true));
angles.push_back(make_pair(beta, false));
}
}

// angles vector is sorted and traversed


sort(angles.begin(), angles.end());

// count maintains the number of points inside


// the circle at certain value of theta
// res maintains the maximum of all count
int count = 1, res = 1;
vector<pair<double, bool> >::iterator it;
for (it=angles.begin(); it!=angles.end(); ++it)
{
// entry angle
if ((*it).second)
count++;

// exit angle
else
count--;

if (count > res)


res = count;
}

return res;
}

// Returns count of maximum points that can lie


// in a circle of radius r.
int maxPoints(Point arr[], int n, int r)
{
// dis array stores the distance between every
// pair of points
for (int i=0; i<n-1; i++)
for (int j=i+1; j<n; j++)

// abs gives the magnitude of the complex


// number and hence the distance between
// i and j
dis[i][j] = dis[j][i] = abs(arr[i]-arr[j]);

// This loop picks a point p


int ans = 0;
for (int i=0; i<n; i++)
// maximum number of points for point arr[i]
ans = max(ans, getPointsInside(i, r, n));

return ans;
}

// Driver code
int main()
{
Point arr[] = {Point(6.47634, 7.69628),
Point(5.16828, 4.79915),
Point(6.69533, 6.20378)};
int r = 1;

int n = sizeof(arr)/sizeof(arr[0]);

cout << "The maximum number of points are: "


<< maxPoints(arr, n, r);

return 0;
}

Check if a line touches or intersects a circle


// CPP program to check if a line touches or
// intersects or outside a circle.
#include <bits/stdc++.h>
using namespace std;

void checkCollision(int a, int b, int c,


int x, int y, int radius)
{
// Finding the distance of line from center.
int dist = (abs(a * x + b * y + c)) /
sqrt(a * a + b * b);

// Checking if the distance is less than,


// greater than or equal to radius.
if (radius == dist)
cout << "Touch" << endl;
else if (radius > dist)
cout << "Intersect" << endl;
else
cout << "Outside" << endl;
}

// Driven Program
int main()
{
int radius = 5;
int x = 0, y = 0;
int a = 3, b = 4, c = 25;
checkCollision(a, b, c, x, y, radius);
return 0;
}

// CPP program to check whether circle with given


// co-ordinates reside within the boundary
Check whether given circle resides in boundary maintained by
two other circles
// of outer circle and inner circle
#include <bits/stdc++.h>
using namespace std;

// function to check if given circle fit in


// boundary or not
void fitOrNotFit(int R, int r, int x, int y,
int rad) {

// Distance from the center


double val = sqrt(pow(x, 2) + pow(y, 2));

// Checking the corners of circle


if (val + rad <= R && val - rad >= R - r)
cout << "Fits\n";
else
cout << "Doesn't Fit\n";
}

// driver program
int main()
{
// Radius of outer circle and inner circle
// respectively
int R = 8, r = 4;

// Co-ordinates and radius of the circle


// to be checked
int x = 5, y = 3, rad = 3;
fitOrNotFit(R, r, x, y, rad);
return 0;
}

Minimum circle problem


#include<bits/stdc++.h>

using namespace std;

typedef long double dbl;

const dbl eps = 1e-9;

inline bool gt(const dbl & x, const dbl & y){

return x > y + eps;

}
inline bool lt(const dbl & x, const dbl & y){

return y > x + eps;

inline dbl safe_sqrt(const dbl & D){

return D < 0 ? 0 : sqrt(D);

struct pt{

dbl x, y;

pt(){}

pt(dbl a, dbl b):x(a), y(b){}

};

const int N = 1e5 + 5;

const int STEPS = 150;

int n;

pt p[N];

inline bool can(dbl R){

dbl l = -1e16 - 1, r = 1e16 + 1;

for(int i = 0; i < n; i++){

dbl b = -2 * p[i].x;

dbl c = p[i].x * p[i].x + p[i].y * p[i].y - 2 * p[i].y * R;

dbl D = b * b - 4 * c;

if(lt(D, 0))
return false;

D = safe_sqrt(D);

dbl x1 = p[i].x - D/2, x2 = p[i].x + D/2;

l = max(l, x1);

r = min(r, x2);

return !gt(l, r);

int main(){

ios_base::sync_with_stdio(false);

cin.tie(0);

cin >> n;

bool has_positive = false, has_negative = false;

for(int i = 0; i < n; i++){

int x, y;

cin >> x >> y;

p[i] = pt(x, y);

if(y > 0)has_positive = true;

else has_negative = true;

if(has_positive && has_negative){

cout << -1 << endl;

return 0;

}
if(has_negative){

for(int i = 0; i < n; i++)

p[i].y = -p[i].y;

dbl L = 0, R = 1e16;

std::function<dbl(dbl, dbl)> get_mid;

if(can(1)){

R = 1;

get_mid = [](dbl l, dbl r){return (l + r)/2.0;};

else{

L = 1;

get_mid = [](dbl l, dbl r){return sqrt(l * r);};

for(int step = 0; step < STEPS; step++){

dbl mid = get_mid(L, R);

if(can(mid))

R = mid;

else

L = mid;

cout.precision(16);

cout << fixed << get_mid(L, R) << endl;

You might also like