@@ -66,16 +66,33 @@ public function stringPermutations(string $string): array {
66
66
*/
67
67
private function permute (array $ objects , $ prefix , array $ result ) {
68
68
$ length = \count ($ objects );
69
+ //if there are no elements in the array,
70
+ //a permutation is found. The permutation is
71
+ //added to the array
69
72
if (0 === $ length ) {
70
73
$ result [] = $ prefix ;
71
- } else {
74
+ }
75
+ //if the number of elements in the array
76
+ //is greater than 0, there are more elements
77
+ //to build an permutation.
78
+ else {
79
+ //The length is decreased by each recursive function call
72
80
for ($ i = 0 ; $ i < $ length ; $ i ++) {
81
+ //a new prefix is created. The prefix consists of the
82
+ //actual prefix ("" at the beginning) and the next element
83
+ //in the objects array
84
+ $ newPrefix = $ prefix . $ objects [$ i ];
85
+
86
+ //since the ith element in objects is used as a prefix,
87
+ //the remaining objects have to be sliced by exactly this
88
+ //object in order to prevent a reoccurrence of the element in
89
+ //the permutation
73
90
$ newObjects = \array_merge (
74
91
\array_slice ($ objects , 0 , $ i ),
75
92
\array_slice ($ objects , $ i + 1 )
76
93
);
77
- $ newPrefix = $ prefix . $ objects [$ i ];
78
94
95
+ //call the permute method with the new prefix and objects
79
96
$ result = $ this ->permute ($ newObjects , $ newPrefix , $ result );
80
97
}
81
98
}
0 commit comments