計算排列組合的php代碼

來源:互聯網
上載者:User

前些天因為業務需要寫了一段計算排列組合的代碼,今天整理了一下,以備後用

<?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);
?>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.