<?php
/*
功能:求隨意四個點是否能組成四邊形php
給你四個座標點,判斷它們能不能組成一個矩形,如判斷([0,0],[0,1],[1,1],[1,0])能組成一個矩形。html
咱們分析這道題, 給4個標點,判斷是否矩形數組
高中知識,矩形有4條邊,兩兩相等, 矩形兩條對角線相等, 矩形的長短邊與對角線知足勾股定理。htm
故解題思路爲,根據座標點,blog
列出全部的兩點組合邊長的數組,去重,看是否是隻剩 3個長度(注意正方形2個長度)get
判斷是否知足勾股定理博客
調優一下,先判斷有沒有重複的點,有的話確定不是矩形io
*/function
代碼以下:class
function isRectangle($point1, $point2, $point3, $point4){
if ($point1 == $point2 || $point1 == $point3 || $point1 == $point4 || $point2 == $point3 || $point2 == $point4 || $point3 == $point4) {
return false;
}
$lengthArr = [];
$lengthArr[] = getLengthSquare($point1, $point2);
$lengthArr[] = getLengthSquare($point1, $point3);
$lengthArr[] = getLengthSquare($point1, $point4);
$lengthArr[] = getLengthSquare($point2, $point3);
$lengthArr[] = getLengthSquare($point2, $point4);
$lengthArr[] = getLengthSquare($point3, $point4);
$lengthArr = array_unique($lengthArr);
$lengthCount = count($lengthArr);
if ($lengthCount == 3 || $lengthCount == 2 ) {
if ($lengthCount == 2) {
return(max($lengthArr) == 2*min($lengthArr));
} else {
$maxLength = max($lengthArr);
$minLength = min($lengthArr);
$otherLength = array_diff($lengthArr, [$maxLength, $minLength]);
return($minLength + $otherLength == $maxLength);
}
} else {
return false;
}
}
function getLengthSquare($point1, $point2){
$res = pow($point1[0]-$point2[0], 2)+pow($point1[1]-$point2[1], 2);
return $res;
}
var_dump(isRectangle([0,0],[0,1],[1,1],[1,0]));
感謝https://www.cnblogs.com/jwcrxs/p/8986120.html此博客的分享