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]));
  • 相关阅读:
    求多边形的面积
    Sequence operation3397
    Atlantis1542(线段树求矩形覆盖面积)
    hdu3033 分组背包(每组最少选一个)
    poj3468A Simple Problem with Integers(线段树延时更新)
    Picture 1828
    Minimum Inversion Number 1394(线段树法)
    hdu2955 Robberies 01背包
    C# 对MongoDB数据库进行增删该
    C#连接MongoDB数据库应用实战
  • 原文地址:https://www.cnblogs.com/jwcrxs/p/8986120.html
Copyright © 2011-2022 走看看