- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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, the code is as follows −
Example
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; } # initialise 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 as well 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" }
The first iteration indicates the same set of characters to be displayed. If the size is 1, then the combination is displayed. An array is initialized as ‘new_combinations’ and it is looped through using the ‘forloop’ and every character in that string is concatenated with every other character. The function ‘sampling’ is called with the parameters (string, the size of the string and the array).
Advertisements