吴峰的博客

矩形:

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

思路:

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

注意:

  正方形是特殊的矩形。

 

代码附上:

    //获取两个点之间的长度的平方

    //不计算边长是为了后面方便进行比较

    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]));


Tags:
PHP
评论 (0)
    说点什么吧... (取消回复)

    正在加载验证码......

    请先拖动验证码到相应位置

Copyright 吴峰的博客 © 2014-2016 管理员邮箱:phpwufeng@163.com   统计:   ICP备案:鲁ICP备16004939号-1