
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check if Two Parallel Lines Contain All Coordinates in C++
In this article, we will be discussing a program to find whether only two parallel lines can hold all the given coordinates points.
For this we will be given an array, such that the coordinates will be (i, arr[i]). Let us suppose we are given an array,
arr = {2,6,8,12,14}
Then we can have these points on two parallel lines, the first line containing (1,2), (3,8) and (5,14). The second line having the rest coordinates i.e (2,6) and (4,12).
This problem can be solved by comparing the slopes of the lines made by the given lines. As we know, the slope of a line made by (a1,b1) and (a2,b2) is (b2-b1)/(a2-a1).
Similarly we can have three points from the given array and compare their slopes. Since we have only two lines, among the three points, two of them have to be on the same line.
To do this, we will take three points and calculate the intercept line through them makes. If we get exactly two different values of the intercept, then the points in array can be represented on two parallel lines, otherwise not.
The program returns 1 if the condition is possible, otherwise 0.
Example
#include <bits/stdc++.h> using namespace std; //to calculate if we get exactly two values of intercept bool is_intercept(double slope, int arr[], int num) { set<double> Lines; for (int i = 0; i < num; i++) Lines.insert(arr[i] - slope * (i)); return Lines.size() == 2; } //to check the slope of the given points bool is_parallel(int arr[], int num) { bool slope1 = is_intercept(arr[1] - arr[0], arr, num); bool slope2 = is_intercept(arr[2] - arr[1], arr, num); bool slope3 = is_intercept((arr[2] - arr[0]) / 2, arr, num); return (slope1 || slope2 || slope3); } int main() { int arr[] = {2,6,8,12,14}; int num = sizeof(arr)/sizeof(arr[0]); cout << (int)is_parallel(arr, num); return 0; }
Output
1