Skip to content

Commit 0575cae

Browse files
committed
array util sum collection
1 parent fd5664e commit 0575cae

File tree

1 file changed

+43
-1
lines changed

1 file changed

+43
-1
lines changed

src/Util/ArrayUtil.php

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ private function __construct() {
4141
/**
4242
* converts an array to a string using $delimiter as the delimiter between the elements
4343
*
44-
* @param array $array
44+
* @param array $array
4545
* @param string $delimiter
4646
* @return string
4747
*/
@@ -56,4 +56,46 @@ public static function arrayToString(array $array, $delimiter = ""): string {
5656
}
5757
return $string;
5858
}
59+
60+
/**
61+
* returns a boolean that indicates whether a sequence sums up to a value or not
62+
*
63+
* @param array $numbers
64+
* @param int $target
65+
* @return bool
66+
*/
67+
public static function hasSum(array $numbers, int $target): bool {
68+
$collection = ArrayUtil::sumCollection($numbers, $target);
69+
if (null === $collection) return false;
70+
if (0 === \count($collection)) return false;
71+
return true;
72+
}
73+
74+
/**
75+
* returns an array that contains all numbers that sums up to $val
76+
*
77+
* @param array $numbers
78+
* @param int $target
79+
* @return array|null
80+
*/
81+
public static function sumCollection(array $numbers, int $target): ?array {
82+
$size = count($numbers);
83+
if ($size < 3) return null;
84+
$collection = [];
85+
86+
for ($i = 0; $i < $size; $i++) {
87+
for ($j = $i + 1; $j < $size; $j++) {
88+
for ($k = $j + 1; $k < $size; $k++) {
89+
$sum = $numbers[$i] + $numbers[$j] + $numbers[$k];
90+
91+
if ($sum === $target) {
92+
$collection[] = [$i, $j, $k];
93+
$sum = 0;
94+
}
95+
if ($sum > $target) continue;
96+
}
97+
}
98+
}
99+
return $collection;
100+
}
59101
}

0 commit comments

Comments
 (0)