How to Generate All Combinations of a Specific Size from a Single Set in PHP
Given an array of characters and a desired combination size, the task is to generate all possible combinations of that specific size. This article explores an algorithm to achieve this using PHP, differentiating it from permutations where repeating characters are not allowed.
Algorithm
The algorithm is based on recursion. Here's a detailed explanation:
Example Implementation
Below is a working example in 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); } // Example $chars = array('a', 'b', 'c'); $output = sampling($chars, 2); var_dump($output);
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 Single Set in PHP?. For more information, please follow other related articles on the PHP Chinese website!