Check if Two Points are on the Same Line in Java

Problem:

Suppose a set of points are given. Write a program to check whether all the points are on the same line. Use the following sets to test your program:

double[][] set1 = {{1, 1}, {2, 2}, {3, 3}, {4, 4}};

double[][] set2 = {{0, 1}, {1, 2}, {4, 5}, {5, 6}};

double[][] set3 = {{0, 1}, {1, 2}, {4, 5}, {4.5, 4}};


Output:

How many points do you want to check? 5
Enter point 1 coordinates: 0 1
Enter point 2 coordinates: 1 2
Enter point 3 coordinates: 4 5

Enter point 4 coordinates: 4.5 4
Enter point 5 coordinates: 0 1
Numbers are not on the same line


Solution:

import java.util.Scanner;
public class SameLine
{
  public static boolean sameLine(double[][] sum)
  {
    double slope = (sum[1][1] - sum[0][1]) / (sum[1][0] - sum[0][0]);
    for (int i = 0;i<sum.length;i++)
    {
      for (int j =0;j<sum.length-1;j++)
      {
      if ((sum[j+1][1] - sum[j][1]) /
          (sum[j+1][0] - sum[j][0]) != slope )
        return false;
      }
    }
    return true;
  }
  public static void main (String[] args)
  {
    Scanner scan = new Scanner(System.in);
    System.out.print("How many points do you want to check? ");
    double[][] points = new double[scan.nextInt()][2];
    for (int i =0;i<points.length;i++)
    {
      System.out.print("Enter point " + (i+1) 
                + " coordinates: ");
      points[i][0] = scan.nextDouble();
      points[i][1] = scan.nextDouble();
    }
    if (sameLine(points)) System.out.println("Points are on the same line");
    else
      System.out.println("Numbers are not on the same line");
    
    
  }
}

No comments:

Post a Comment