Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Generate all combinations of a specific size from a single set in PHP
To generate all combinations of a specific size from a single set in PHP, we can use a recursive function that builds combinations by concatenating characters from the original set.
Example
Here's a function that generates all possible combinations of a specified size from a character set ?
<?php
function sampling($chars, $size, $combinations = array()) {
// In case of first iteration, the first set of combinations is the same as the set of characters
if (empty($combinations)) {
$combinations = $chars;
}
// Size 1 indicates we are done
if ($size == 1) {
return $combinations;
}
// Initialize array to put new values into it
$new_combinations = array();
// Loop through the existing combinations and character set to create strings
foreach ($combinations as $combination) {
foreach ($chars as $char) {
$new_combinations[] = $combination . $char;
}
}
// Call the same function again for the next iteration
return sampling($chars, $size - 1, $new_combinations);
}
$chars = array('a', 'b', 'c');
$output = sampling($chars, 2);
var_dump($output);
?>
Output
This will produce the following output ?
array(9) {
[0]=>
string(2) "aa"
[1]=>
string(2) "ab"
[2]=>
string(2) "ac"
[3]=>
string(2) "ba"
[4]=>
string(2) "bb"
[5]=>
string(2) "bc"
[6]=>
string(2) "ca"
[7]=>
string(2) "cb"
[8]=>
string(2) "cc"
}
How It Works
The function works recursively by building combinations layer by layer. In the first iteration, it uses the original character set. For each subsequent iteration, it concatenates every existing combination with every character from the original set, creating combinations of increasing length until the desired size is reached.
Example with Different Size
Here's another example generating combinations of size 3 ?
<?php
function sampling($chars, $size, $combinations = array()) {
if (empty($combinations)) {
$combinations = $chars;
}
if ($size == 1) {
return $combinations;
}
$new_combinations = array();
foreach ($combinations as $combination) {
foreach ($chars as $char) {
$new_combinations[] = $combination . $char;
}
}
return sampling($chars, $size - 1, $new_combinations);
}
$chars = array('x', 'y');
$output = sampling($chars, 3);
print_r($output);
?>
Array
(
[0] => xxx
[1] => xxy
[2] => xyx
[3] => xyy
[4] => yxx
[5] => yxy
[6] => yyx
[7] => yyy
)
Conclusion
This recursive approach efficiently generates all possible combinations with repetition of a specified size from any given set. The function creates n^size combinations where n is the number of elements in the original set.
