From ebd709d4cb9917ec18e569429a3d4efd486a7683 Mon Sep 17 00:00:00 2001 From: Dennis Eichhorn Date: Fri, 5 Jun 2020 09:51:47 +0200 Subject: [PATCH] impl. early return --- Math/Geometry/ConvexHull/MonotoneChain.php | 49 +++++++++++----------- 1 file changed, 25 insertions(+), 24 deletions(-) diff --git a/Math/Geometry/ConvexHull/MonotoneChain.php b/Math/Geometry/ConvexHull/MonotoneChain.php index 851c80843..7b5639a57 100644 --- a/Math/Geometry/ConvexHull/MonotoneChain.php +++ b/Math/Geometry/ConvexHull/MonotoneChain.php @@ -45,36 +45,37 @@ final class MonotoneChain */ public static function createConvexHull(array $points) : array { - if (($n = \count($points)) > 1) { - \uasort($points, [self::class, 'sort']); + if (($n = \count($points)) < 2) { + return $points; + } + + \uasort($points, [self::class, 'sort']); - $k = 0; - $result = []; + $k = 0; + $result = []; - // Lower hull - for ($i = 0; $i < $n; ++$i) { - while ($k >= 2 && self::cross($result[$k - 2], $result[$k - 1], $points[$i]) <= 0) { - --$k; - } - - $result[$k++] = $points[$i]; + // Lower hull + for ($i = 0; $i < $n; ++$i) { + while ($k >= 2 && self::cross($result[$k - 2], $result[$k - 1], $points[$i]) <= 0) { + --$k; } - // Upper hull - for ($i = $n - 2, $t = $k + 1; $i >= 0; --$i) { - while ($k >= $t && self::cross($result[$k - 2], $result[$k - 1], $points[$i]) <= 0) { - --$k; - } - - $result[$k++] = $points[$i]; - } - - \ksort($result); - - return \array_slice($result, 0, $k - 1); + $result[$k++] = $points[$i]; } - return $points; + // Upper hull + for ($i = $n - 2, $t = $k + 1; $i >= 0; --$i) { + while ($k >= $t && self::cross($result[$k - 2], $result[$k - 1], $points[$i]) <= 0) { + --$k; + } + + $result[$k++] = $points[$i]; + } + + \ksort($result); + + /** @return array */ + return \array_slice($result, 0, $k - 1); } /**