The description of the problem is very simple. Given the coordinates of some points, return true if they are on the same straight line.
For example, [7, 4], this represents a point.
onLine([[1,2], [7, 4], [22, 9]]); // returns true onLine([[1,2], [-3, -14], [22, 9]]); // returns false
When I saw this question, I first imagined a plane in my mind, and then a rectangular coordinate system appeared.
I traced these points on the coordinate system one by one according to the method taught to me by my middle school mathematics teacher.
Then connect the points with line segments.
So, how to judge that they are on the same straight line?
I quickly thought about slope.
If any two points on the straight line are (x1, y1) , (x2, y2) , then the slope of the straight line k= (y2-y1)/ (x2-x1).
If the slopes of these line segments are the same, then they must be on the same straight line!
In the program, I only need to determine the slope between line segments. If it is different, it will return false.
Write the code based on the above ideas:
function onLine(points) { var slope; for(var i=0;i<points.length-1;i++){ var p1 = points[i]; var p2 = points[i+1]; var currentSlope = (p2[1] - p1[1]) / (p2[0] - p1[0]); if(slope){ if(slope !== currentSlope){ return false; } } else{ slope = currentSlope; } } return true; }
The above are interesting JavaScript questions: the content of points, lines, and surfaces, more related Please pay attention to the PHP Chinese website (www.php.cn) for content!