

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 It Is a Straight Line in C++
Suppose we have a list of data-points consisting of (x, y) coordinates, we have to check whether the data-points are forming straight line or not. So if the points are like [(1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7)], then they are forming straight line.
To solve this, we will take the differences between each consecutive datapoints, and find the slope. For the first one find the slope. For all other points check whether the slope is same or not. if they are same, then simply return true, otherwise false
Example
Let us see the following implementation to get a better understanding −
#include <bits/stdc++.h> using namespace std; class Solution { public: int gcd(int a, int b){ return !b?a:gcd(b,a%b); } bool checkStraightLine(vector<vector<int>>& c) { bool ans =true; bool samex = true; bool samey = true; int a = c[1][0]-c[0][0]; int b = c[1][1]-c[0][1]; int cc = gcd(a,b); a/=cc; b/=cc; for(int i =1;i<c.size();i++){ int x = c[i][0]-c[i-1][0]; int y = c[i][1]-c[i-1][1]; int z = gcd(x,y); x/=z; y/=z; ans =ans &&(x == a )&& (y == b ); } return ans; } }; main(){ Solution ob; vector<vector<int>> c = {{1,2},{2,3},{3,4},{4,5},{5,6},{6,7}}; cout << ob.checkStraightLine(c); }
Input
[[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]
Output
1 (1 indicates true)
- Related Questions & Answers
- Check if it is possible to draw a straight line with the given direction cosines in Python
- Check If It Is a Good Array in C++
- Straight Line Method of Calculating Depreciation
- Explain about straight line depreciation in accounting.
- Program to check whether list of points form a straight line or not in Python
- C++ Program to Check if it is a Sparse Matrix
- Planar straight line graphs (PSLGs) in Data Structure
- Check if two line segments intersect
- How to calculate depreciation using straight line method?
- Is it possible in Android to check if a notification is visible or canceled?
- Check if a line passes through the origin in C++
- Check if a line touches or intersects a circle in C++
- Is it possible to check if a String only contains ASCII in java?
- Draw a curve connecting two points instead of a straight line in matplotlib
- Check if it is possible to sort the array after rotating it in Python
Advertisements