Home > Article > Backend Development > How to Generate All Combinations of a Specific Size from a Set?
In statistics, sampling refers to obtaining a subset of a population to represent the entire population. The goal is to generate all possible combinations of a specified size from a given set of elements.
To achieve this, we can employ a recursive algorithm, as demonstrated below:
function sampling($chars, $size, $combinations = array()) { # Initialize the starting combinations as the original set if (empty($combinations)) { $combinations = $chars; } # Base case: stop if we've reached the desired size if ($size == 1) { return $combinations; } $new_combinations = array(); # Iterate over existing combinations and add new characters foreach ($combinations as $combination) { foreach ($chars as $char) { $new_combinations[] = $combination . $char; } } # Call the function recursively to generate the next iteration of combinations return sampling($chars, $size - 1, $new_combinations); }
Example:
$chars = array('a', 'b', 'c'); $output = sampling($chars, 2); # Display the generated combinations var_dump($output); /* Expected 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" } */
The above is the detailed content of How to Generate All Combinations of a Specific Size from a Set?. For more information, please follow other related articles on the PHP Chinese website!