前些天因为业务需要写了一段计算排列组合的代码,今天整理了一下,以备后用
<?php<BR>/**<BR> * 要解决的数学问题 :算出C(a,1) * C(b, 1) * ... * C(n, 1)的组合情况,其中C(n, 1)代表从n个元素里任意取一个元素<BR> *<BR> * 要解决的实际问题样例:某年级有m个班级,每个班的人数不同,现在要从每个班里抽选一个人组成一个小组,<BR> * 由该小组来代表该年级参加学校的某次活动,请给出所有可能的组合<BR> */<BR>/* ################################### 开始计算 ################################### */<BR>/**<BR> * 需要进行排列组合的数组<BR> *<BR> * 数组说明:该数组是一个二维数组,第一维索引代表班级编号,第二维索引代表学生编号<BR> */<BR>$CombinList = array(1 => array("Student10", "Student11"),<BR> 2 => array("Student20", "Student2<i style="color:transparent">本文来源gaodai$ma#com搞$$代**码)网8</i><strong>搞代gaodaima码</strong>1", "Student22"),<BR> 3 => array("Student30"),<BR> 4 => array("Student40", "Student41", "Student42", "Student43"));<BR>/* 计算C(a,1) * C(b, 1) * ... * C(n, 1)的值 */<BR>$CombineCount = 1;<BR>foreach($CombinList as $Key => $Value)<BR>{<BR> $CombineCount *= count($Value);<BR>}<BR>$RepeatTime = $CombineCount;<BR>foreach($CombinList as $ClassNo => $StudentList)<BR>{<BR> // $StudentList中的元素在拆分成组合后纵向出现的最大重复次数<BR> $RepeatTime = $RepeatTime / count($StudentList);<BR> $StartPosition = 1;<BR> // 开始对每个班级的学生进行循环<BR> foreach($StudentList as $Student)<BR> {<BR> $TempStartPosition = $StartPosition;<BR> $SpaceCount = $CombineCount / count($StudentList) / $RepeatTime;<BR> for($J = 1; $J <= $SpaceCount; $J ++)<BR> {<BR> for($I = 0; $I < $RepeatTime; $I ++)<BR> {<BR> $Result[$TempStartPosition + $I][$ClassNo] = $Student;<BR> }<BR> $TempStartPosition += $RepeatTime * count($StudentList);<BR> }<BR> $StartPosition += $RepeatTime;<BR> }<BR>}<BR>/* 打印结果 */<BR>echo "<pre class="prettyprint linenums">";<BR>print_r($Result);<BR>?><BR>