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]));
  • 相关阅读:
    Kafka API: TopicMetadata
    从事件总线和消息队列说起
    Object.defineproperty实现数据和视图的联动
    css3动画-animation
    css3动画-transition
    jquery判断对象的type
    vs如何在运行iis express调试时,不开打新窗口和关闭调试时,iis express不退出
    重写Equals的方式
    Android中包名不能大写
    C# 几种常见数据结构【转】
  • 原文地址:https://www.cnblogs.com/jwcrxs/p/8986120.html
Copyright © 2011-2022 走看看