|
復制代碼 代碼如下:
<?php
/**
* 要解決的數學問題 :算出C(a,1) * C(b, 1) * ... * C(n, 1)的組合情況,其中C(n, 1)代表從n個元素里任意取一個元素
*
* 要解決的實際問題樣例:某年級有m個班級,每個班的人數不同,現在要從每個班里抽選一個人組成一個小組,
* 由該小組來代表該年級參加學校的某次活動,請給出所有可能的組合
*/
/* ################################### 開始計算 ################################### */
/**
* 需要進行排列組合的數組
*
* 數組說明:該數組是一個二維數組,第一維索引代表班級編號,第二維索引代表學生編號
*/
$CombinList = array(1 => 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);
$StartPosition = 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 "<pre>";
print_r($Result);
?>
php技術:使用php計算排列組合的方法,轉載需保留來源!
鄭重聲明:本文版權歸原作者所有,轉載文章僅為傳播更多信息之目的,如作者信息標記有誤,請第一時間聯系我們修改或刪除,多謝。