JavaScript 如何检查给定的四个点是否形成一个正方形(How to check if given four points form a square)

 给定平面上四个点的坐标,判断这四个点是否形成正方形。 

要检查正方形,我们需要检查以下内容:
        a) 由点形成的所有四条边都相同。
        b) 任何两条边之间的角度都是 90 度。(此条件是必需的,因为菱形 也有相同的边)
        c) 检查两条对角线的距离是否相同.

例子:

输入: p1 = { 20, 10 }, p2 = { 10, 20 }, p3 = { 20, 20 }, p4 = { 10, 10 }
输出: 是
解释: 

输入: p1 = { 20, 20 }, p2 = { 10, 20 }, p3 = { 20, 20 }, p4 = { 10, 10 }
输出: 否 

        方法:思路是选取任意一点并计算其与其余点的距离。设选取的点为“p”。要形成正方形,两个点与“p”的距离必须相同,设该距离为 d。与一个点的距离必须不同于 d,并且必须等于 d 的 2 倍。设距离不同的这个点为“q”。 

        上述条件还不够好,因为距离不同的点可能在另一侧。我们还需要检查 q 是否与其他 2 个点的距离相同,并且该距离与 d 相同。

以下是上述想法的实现:

// JavaScript program to check if four given points form a square or not.
 
// A utility function to find square of distance
// from point 'p' to point 'q'
function distSq( p, q){
    return (p.x - q.x) * (p.x - q.x) + (p.y - q.y) * (p.y - q.y);
}
 
// This function returns true if (p1, p2, p3, p4) form a
// square, otherwise false
function isSquare(p1,  p2,  p3, p4){
    let d2 = distSq(p1, p2); // from p1 to p2
    let d3 = distSq(p1, p3); // from p1 to p3
    let d4 = distSq(p1, p4); // from p1 to p4
 
    if (d2 == 0 || d3 == 0 || d4 == 0)    
        return false;
 
    // If lengths if (p1, p2) and (p1, p3) are same, then
    // following conditions must met to form a square.
    // 1) Square of length of (p1, p4) is same as twice
    // the square of (p1, p2)
    // 2) Square of length of (p2, p3) is same
    // as twice the square of (p2, p4)
 
    if (d2 == d3 && 2 * d2 == d4
        && 2 * distSq(p2, p4) == distSq(p2, p3)) {
        return true;
    }
 
    // The below two cases are similar to above case
    if (d3 == d4 && 2 * d3 == d2
        && 2 * distSq(p3, p2) == distSq(p3, p4)) {
        return true;
    }
    if (d2 == d4 && 2 * d2 == d3
        && 2 * distSq(p2, p3) == distSq(p2, p4)) {
        return true;
    }
 
    return false;
}
 
// Driver program to test above function
let p1 = { x:20, y:10 }
let p2 = { x:10, y:20 }
let p3 = { x:20, y:20 }
let p4 = { x:10, y:10 }
isSquare(p1, p2, p3, p4) ? document.write("Yes") : document.write("No");
 
// This code is contributed by rohitsingh07052. 

输出:

时间复杂度: O(1),所有操作都在 O(1) 常数时间内执行。

辅助空间: O(1),不需要额外空间

扩展: 检查四个线段是否形成一个矩形
JavaScript:https://blog.youkuaiyun.com/hefeng_aspnet/article/details/145686594
C#:https://blog.youkuaiyun.com/hefeng_aspnet/article/details/145686569
Python:https://blog.youkuaiyun.com/hefeng_aspnet/article/details/145686543
Java:https://blog.youkuaiyun.com/hefeng_aspnet/article/details/145686509
C++:https://blog.youkuaiyun.com/hefeng_aspnet/article/details/145686317 

如果您喜欢此文章,请收藏、点赞、评论,谢谢,祝您快乐每一天。 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

csdn_aspnet

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值