# Maximum distinct lines passing through a single point in C

CServer Side ProgrammingProgramming

We are given the number N and coordinates of two points (x1,y1) and (x2,y2) for each line. The goal is to find the maximum number of lines from given lines that can pass through a single point such that no two lines cover each other, and no rotation is performed.

We will represent lines as pair of (m,c) where y=mx+c and m is slope m=y2-y1/x2-x1

Lines with same m are parallel given c1!=c2. We will count distinct slopes(m). For vertical lines if x1=x2, slope = INT_MAX else m.

Let us understand with an example.

Input

Line 1 (x1,y1)=(4,10) (x2,y2)=(2,2)
Line 2 (x1,y1)=(2,2) (x2,y2)=(1,1)

Output

Maximum lines: 2

Explanation − Total lines is 2. Both have different slopes.

Input

Line 1 (x1,y1)=(1,5) (x2,y2)=(3,2)
Line 2 (x1,y1)=(2,7) (x2,y2)=(2,8)

Output

Maximum lines: 2

Explanation − Total lines is 2. Both have different slopes.

## Approach used in the below program is as follows

• The integer array x1[] and x2[] are used to store the coordinates of points on lines.

• Function numLines(int x1[],int y1[], int x2[], int y2[]) is counting the number of lines passing through a single point.

• Applying the formula for each point in x1[],y1[],x2[],y2[] to calculate slope and incrementing the slopes count using k.

• Array s[] stores the value of slopes.

• Return k as count of lines in result.

## Example

Live Demo

#include <stdio.h>
int numLines(int n, int x1[], int y1[], int x2[], int y2[]){
double s;
int k=0;
double slope;
for (int i = 0; i < n; ++i) {
if (x1[i] == x2[i])
slope = 999;
else
slope = (y2[i] - y1[i]) * 1.0 / (x2[i] - x1[i]) * 1.0;
s[k++]=slope;
}
return k;
}
int main(){
int n = 2;
int x1[] = { 1, 5 }, y1[] = { 3, 2 };
int x2[] = { 2,7 }, y2[] = { 2, 8 };
printf("Maximum lines: %d", numLines(n, x1, y1, x2, y2));
return 0;
}

## Output

If we run the above code it will generate the following output −

Maximum distinct lines passing through a single point : 2