Check If It Is a Straight Line in C++

C++Server Side ProgrammingProgramming

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 −

 Live Demo

#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)
raja
Updated on 29-Apr-2020 08:07:21

Advertisements