![]() |
JavaScript allows us to check If the given line is a Straight Line or not. 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: There are several approaches to Check If It Is a Straight Line in JavaScript which are as follows: Table of Content 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:
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 true 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 |