@@ -41,7 +41,7 @@ private function __construct() {
41
41
/**
42
42
* converts an array to a string using $delimiter as the delimiter between the elements
43
43
*
44
- * @param array $array
44
+ * @param array $array
45
45
* @param string $delimiter
46
46
* @return string
47
47
*/
@@ -56,4 +56,46 @@ public static function arrayToString(array $array, $delimiter = ""): string {
56
56
}
57
57
return $ string ;
58
58
}
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
+ }
59
101
}
0 commit comments