एक सेट से एक विशिष्ट आकार के सभी संयोजन उत्पन्न करने के लिए, कोड इस प्रकार है -
उदाहरण
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); आउटपुट
यह निम्नलिखित आउटपुट देगा -
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" } पहला पुनरावृत्ति प्रदर्शित होने वाले वर्णों के समान सेट को इंगित करता है। यदि आकार 1 है, तो संयोजन प्रदर्शित होता है। एक सरणी को 'new_combinations' के रूप में प्रारंभ किया जाता है और इसे 'forloop' का उपयोग करके लूप किया जाता है और उस स्ट्रिंग के प्रत्येक वर्ण को हर दूसरे वर्ण के साथ जोड़ा जाता है। फ़ंक्शन 'नमूनाकरण' को पैरामीटर (स्ट्रिंग, स्ट्रिंग का आकार और सरणी) के साथ कहा जाता है।