Check if Coordinates make a Straight Line | Array Problem

4 years ago Lalit Bhagtani 0

Problem Statement

You have given an array of coordinates, write a program to find out if an array of coordinates make a straight line in the 2D plane.

Each coordinate is an array of two values x and y, where x represents a coordinate point on X-axis and y represents the coordinate point on Y-axis of 2D plane.

Example 

Input :- [[1,2], [2,3], [3,4], [4,5], [5,6], [6,7]]
Output :- true

Input :- [[1,1], [2,2], [3,5], [6,2], [5,6], [7,7]]
Output :- false

Solution

The straight line has only one slope. It means that the slope between any two coordinates lying on the straight line is same.

Slope = Y2 - Y1 / X2 - X1

Now to solve this problem, we have to iterate through the array of coordinates and calculate the slope between every pair of coordinates. If all calculated slopes are the same, then the straight line can be drawn using these coordinates, otherwise not.

Program

public class Main {

	public static void main(String[] args) {		
		Main main = new Main();
		boolean result = main.checkStraightLine(new int[][] {{1, 2}, {2, 3}, {3, 4}, {4, 5}, {5, 6}, {6, 7}});
		System.out.print(result);										
	}  
	
	/* Solution */    
	public boolean checkStraightLine(int[][] coordinates) {
                
        int xChange = coordinates[1][0] - coordinates[0][0];
        int yChange = coordinates[1][1] - coordinates[0][1];        
        
        int xChangeN = 0, yChangeN = 0;
        for(int i=2; i<coordinates.length; i++){   
        	
        	xChangeN = coordinates[i][0] - coordinates[i-1][0];
        	yChangeN = coordinates[i][1] - coordinates[i-1][1];
            if(xChange * yChangeN != yChange * xChangeN){
                return false;
            } 
        }
        return true;
    }
}

Result

true 

Similar Post

  1. Design Min Stack Data Structure
  2. Design Max Stack Data Structure
  3. Design Maximum Frequency Stack Data Structure

That’s all for Check if Coordinates make a Straight Line in Java, If you liked it, please share your thoughts in a comments section and share it with others too.