给四个坐标点,判断能否构成一个矩形(php)

矩形:

  矩形对角线相等,且四个角为直角。所以可以根据勾股定理判定。

思路:

  首先判断坐标点是否有重复,然后四个坐标点可以求得它们两两之间的距离,只要两条短边的平方相加等于长边平方即可判定它为矩形。

注意:

  正方形是特殊的矩形。

代码附上:

<?php 

    //获取两个点之间的长度的平方
    //不计算边长是为了后面方便进行比较
    function getLength($point1, $point2){
        $res = pow($point1[0]-$point2[0], 2) + pow($point1[1]-$point2[1], 2);
        return $res;
    }

    function judgeRectangle($point1, $point2, $point3, $point4){
        //任意两点相同 不可能组成矩形
        if($point1 == $point2 || $point1 == $point3 || $point1 == $point4 || $point2 == $point3 || $point2 == $point4 || $point3 == $point4){
            return false;
        }

        //将所有边长平方放在一个数组内
        $arr = [];
        $arr[] = getLength($point1, $point2);
        $arr[] = getLength($point1, $point3);
        $arr[] = getLength($point1, $point4);
        $arr[] = getLength($point2, $point3);
        $arr[] = getLength($point2, $point4);
        $arr[] = getLength($point3, $point4);

        //去重
        $arr = array_unique($arr);
        $arr_count = count($arr);

        //正方形也是矩形
        if($arr_count == 3 || $arr_count == 2){
            $max_length = max($arr);
            $min_length = min($arr);
            $other_length = array_diff($arr, [$max_length, $min_length]);

            //勾股定理
            if($min_length + $other_length = $max_length){
                return true;
            } else {
                return false;
            }

        } else {
            return false;
        }
    }

    var_dump(judgeRectangle([0,0], [0,5], [2,0], [2,6]));

猜你喜欢

转载自www.cnblogs.com/nuanyingzi/p/11756071.html
今日推荐