
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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 Articles
- Check if it is possible to draw a straight line with the given direction cosines in Python
- what is a straight line in angles
- What can you say about the motion of a body if:$(a)$. its displacement-time graph is a straight line?$(b)$. its velocity-time graph is a straight line?
- Is a straight line an example of a polygon?
- Check If It Is a Good Array in C++
- Program to check whether list of points form a straight line or not in Python
- What is the motion when something moves in a straight line?
- FabricJS – How to check if a specified control is visible in Line?
- If i am drawing a straight line without lifting my pencil then that is also a curve?
- What does a straight line graph indicates?
- Why does light only travel in a straight line?
- Check if a line passes through the origin in C++
- Check if a line touches or intersects a circle in C++
- Check if two line segments intersect
- C++ Program to Check if it is a Sparse Matrix

Advertisements