Home > Web Front-end > JS Tutorial > Interesting JavaScript questions: points, lines, and surfaces

Interesting JavaScript questions: points, lines, and surfaces

黄舟
Release: 2017-02-13 16:19:50
Original
1244 people have browsed it

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
Copy after login

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;
}
Copy after login


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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template