단일 세트에서 특정 크기의 모든 조합을 생성하려면 코드는 다음과 같습니다. -
예시
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'를 사용하여 반복되며 해당 문자열의 모든 문자는 다른 모든 문자와 연결됩니다. 'sampling' 함수는 매개변수(문자열, 문자열의 크기 및 배열)와 함께 호출됩니다.