![]() |
In this article, we are going to learn how we can check whether the given line is a Straight line or not using JavaScript. There are several methods of checking if the given line is straight or not in JavaScript. Below is an example to understand the problem clearly. Example: Input: points = [[1, 2], [2, 3], [3, 4], [4, 5]] Below are different approaches to Check If It Is a Straight Line in JavaScript: Using Slope CalculationDefine a function that takes an array of coordinates as parameter. Get the x and y coordinates of the first two points from the coordinates array. Compute the slope between the first two points using the formula (y1 – y0) / (x1 – x0). Iterate through the remaining coordinates starting from index 2. For each point, calculate the slope between that point and the first point, and compare it with the initial slope. If slopes are not equal, return false else return true. Example: To demonstrate checking If It Is a straight line in JavaScript using slope calculation approach.
Output true Time complexity: O(n) Space complexity: O(1) Using Matrix Determinant ApproachDefine a function that takes an array of coordinates as its parameter. Get the x and y coordinates of the first two points from the coordinates array. Calculate the coefficients A, B, and C by using formula: A = y1 – y0 Iterate through the remaining coordinates starting from index 2. For each point, calculate the expression Ax + By + C and check if it equals 0. If expression is not equal to 0, return false else return true. Example: To demonstrate checking If It Is a straight line in JavaScript using matrix determinant approach.
Output false Time complexity: O(n) Space complexity: O(1) Using Cross Product MethodThe cross product method is another effective way to determine if a set of points lies on a straight line. This method involves calculating the cross product of vectors formed by consecutive points. If the cross product is zero for all consecutive vectors, the points lie on a straight line. Example:
Output true false Time Complexity: O(n) Space Complexity: O(1) |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 14 |