Home>Article>Backend Development> PHP method sample code for calculating permutations and combinations
Permutation and combination are the most basic concepts of combinatorics. The so-called arrangement means to sort a specified number of elements from a given number of elements. Combination refers to taking out only a specified number of elements from a given number of elements, regardless of sorting. The central problem of permutations and combinations is to study the total number of possible situations for permutations and combinations of given requirements. Permutation and combination are closely related to classical probability theory.
The mathematical problem to be solved in this article using PHP is to calculate the combination of C(a,1) * C(b, 1) * ... * C(n, 1), where C(n, 1 ) represents randomly selecting an element from n elements
A few days ago, due to business needs, I wrote a piece of code to calculate permutations and combinations. Today I sorted it out for future use
The code is as follows:
array("Student10", "Student11"), 2 => array("Student20", "Student21", "Student22"), 3 => array("Student30"), 4 => array("Student40", "Student41", "Student42", "Student43")); /* 计算C(a,1) * C(b, 1) * ... * C(n, 1)的值 */ $CombineCount = 1; foreach ($CombinList as $Key => $Value) { $CombineCount *= count($Value); } $RepeatTime = $CombineCount; foreach($CombinList as $ClassNo => $StudentList) { // $StudentList中的元素在拆分成组合后纵向出现的最大重复次数 $RepeatTime = $RepeatTime / count($StudentList); $Start Position = 1; // 开始对每个班级的学生进行 循环 foreach($StudentList as $Student) { $TempStartPosition = $StartPosition; $SpaceCount = $CombineCount / count($StudentList) / $RepeatTime; for($J = 1; $J <= $SpaceCount; $J ++) { for($I = 0; $I < $RepeatTime; $I ++) { $Result[$TempStartPosition + $I][$ClassNo] = $Student; } $TempStartPosition += $RepeatTime * count($StudentList); } $StartPosition += $RepeatTime; } } /* 打印结果 */ echo ""; print_r($Result); ?>
The above is the detailed content of PHP method sample code for calculating permutations and combinations. For more information, please follow other related articles on the PHP Chinese website!