PHP algorithm to generate all combinations of a specific size from a single set -
i trying deduce algorithm generates possible combinations of specific size function accepts array of chars , size parameter , return array of combinations.
example: let have set of chars: set = {a,b,c}
a) possible combinations of size 2: (3^2 = 9)
aa, ab, ac ba, bb, bc ca, cb, cc
b) possible combinations of size 3: (3^3 = 27)
aaa, aab, aac, aba, abb, acc, caa, baa, bac, .... ad on total combinations = 27
please note pair size can greater total size of pouplation. ex. if set contains 3 characters can create combination of size 4.
edit: note different permutation. in permutation cannot have repeating characters example aa cannot come if use permutation algorithm. in statistics known sampling.
i use recursive function. here's (working) example comments. hope works you!
function sampling($chars, $size, $combinations = array()) { # if it's first iteration, first set # of combinations same set of characters if (empty($combinations)) { $combinations = $chars; } # we're done if we're @ size 1 if ($size == 1) { return $combinations; } # initialise array put new values in $new_combinations = array(); # loop through existing combinations , character set create strings foreach ($combinations $combination) { foreach ($chars $char) { $new_combinations[] = $combination . $char; } } # call same function again next iteration return sampling($chars, $size - 1, $new_combinations); } // example $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" } */
Comments
Post a Comment