Skip to content

Commit

Permalink
array util sum collection
Browse files Browse the repository at this point in the history
  • Loading branch information
doganoo committed Dec 12, 2018
1 parent fd5664e commit 0575cae
Showing 1 changed file with 43 additions and 1 deletion.
44 changes: 43 additions & 1 deletion src/Util/ArrayUtil.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ private function __construct() {
/**
* converts an array to a string using $delimiter as the delimiter between the elements
*
* @param array $array
* @param array $array
* @param string $delimiter
* @return string
*/
Expand All @@ -56,4 +56,46 @@ public static function arrayToString(array $array, $delimiter = ""): string {
}
return $string;
}

/**
* returns a boolean that indicates whether a sequence sums up to a value or not
*
* @param array $numbers
* @param int $target
* @return bool
*/
public static function hasSum(array $numbers, int $target): bool {
$collection = ArrayUtil::sumCollection($numbers, $target);
if (null === $collection) return false;
if (0 === \count($collection)) return false;
return true;
}

/**
* returns an array that contains all numbers that sums up to $val
*
* @param array $numbers
* @param int $target
* @return array|null
*/
public static function sumCollection(array $numbers, int $target): ?array {
$size = count($numbers);
if ($size < 3) return null;
$collection = [];

for ($i = 0; $i < $size; $i++) {
for ($j = $i + 1; $j < $size; $j++) {
for ($k = $j + 1; $k < $size; $k++) {
$sum = $numbers[$i] + $numbers[$j] + $numbers[$k];

if ($sum === $target) {
$collection[] = [$i, $j, $k];
$sum = 0;
}
if ($sum > $target) continue;
}
}
}
return $collection;
}
}

0 comments on commit 0575cae

Please sign in to comment.