給四個坐標點,判斷能否構成一個矩形(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]));

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM