給你四個坐標點,判斷它們能不能組成一個矩形,如判斷([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]));

 


免責聲明!

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



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