zoukankan      html  css  js  c++  java
  • 给你四个坐标点,判断它们能不能组成一个矩形,如判断([0,0],[0,1],[1,1],[1,0])能组成一个矩形(面试题)

    给你四个坐标点,判断它们能不能组成一个矩形,如判断([0,0],[0,1],[1,1],[1,0])能组成一个矩形。

    我们分析这道题, 给4个标点,判断是否矩形

    高中知识,矩形有4条边,两两相等, 矩形两条对角线相等, 矩形的长短边与对角线满足勾股定理。

    故解题思路为,根据坐标点,

      列出所有的两点组合边长的数组,去重,看是不是只剩 3个长度(注意正方形2个长度)

      判断是否满足勾股定理

      调优一下,先判断有没有重复的点,有的话肯定不是矩形

    代码如下:

     1 <?php
     2 
     3 
     4 function isRectangle($point1, $point2, $point3, $point4){
     5     if ($point1 == $point2 || $point1 == $point3  || $point1 == $point4 || $point2 == $point3 || $point2 == $point4 || $point3 == $point4) {
     6         return false;
     7     }
     8     $lengthArr = [];
     9     $lengthArr[] = getLengthSquare($point1, $point2);
    10     $lengthArr[] = getLengthSquare($point1, $point3);
    11     $lengthArr[] = getLengthSquare($point1, $point4);
    12     $lengthArr[] = getLengthSquare($point2, $point3);
    13     $lengthArr[] = getLengthSquare($point2, $point4);
    14     $lengthArr[] = getLengthSquare($point3, $point4);
    15 
    16     $lengthArr = array_unique($lengthArr);
    17     $lengthCount = count($lengthArr);
    18     if ($lengthCount == 3 || $lengthCount == 2 ) {
    19         if ($lengthCount == 2) {
    20             return(max($lengthArr) == 2*min($lengthArr));
    21         } else {
    22             $maxLength = max($lengthArr);
    23             $minLength = min($lengthArr);
    24             $otherLength = array_diff($lengthArr, [$maxLength, $minLength]);
    25             return($minLength + $otherLength == $maxLength);
    26         }
    27     } else {
    28         return false;
    29     }
    30 }
    31 
    32 function getLengthSquare($point1, $point2){
    33     $res = pow($point1[0]-$point2[0], 2)+pow($point1[1]-$point2[1], 2);
    34     return $res;
    35 }
    36 
    37 var_dump(isRectangle([0,0],[0,2],[2,2],[2,0]));
  • 相关阅读:
    SQL Server 2005中的分区表(六):将已分区表转换成普通表
    关于SQL Server中分区表的文件与文件组的删除(转)
    MySQL修改root密码的几种方法
    Aptana 插件 for Eclipse 4.4
    IT励志与指导文章合集(链接)
    正则表达式(转)
    《疯狂原始人》温馨而搞笑片段截图
    指针函数与函数指针的区别(转)
    Linux内核@系统组成与内核配置编译
    2015年我国IT行业发展趋势分析(转)
  • 原文地址:https://www.cnblogs.com/jwcrxs/p/8986120.html
Copyright © 2011-2022 走看看