欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

使用php計(jì)算排列組合的方法

 更新時(shí)間:2013年11月13日 09:48:33   作者:  
本文用PHP要解決的數(shù)學(xué)問(wèn)題是算出C(a,1) * C(b, 1) * ... * C(n, 1)的組合情況,其中C(n, 1)代表從n個(gè)元素里任意取一個(gè)元素
前些天因?yàn)闃I(yè)務(wù)需要寫了一段計(jì)算排列組合的代碼,今天整理了一下,以備后用
復(fù)制代碼 代碼如下:

<?php
/**
 * 要解決的數(shù)學(xué)問(wèn)題    :算出C(a,1) * C(b, 1) * ... * C(n, 1)的組合情況,其中C(n, 1)代表從n個(gè)元素里任意取一個(gè)元素
 *
 * 要解決的實(shí)際問(wèn)題樣例:某年級(jí)有m個(gè)班級(jí),每個(gè)班的人數(shù)不同,現(xiàn)在要從每個(gè)班里抽選一個(gè)人組成一個(gè)小組,
 *                       由該小組來(lái)代表該年級(jí)參加學(xué)校的某次活動(dòng),請(qǐng)給出所有可能的組合
 */
/* ################################### 開(kāi)始計(jì)算 ################################### */
/**
 * 需要進(jìn)行排列組合的數(shù)組
 *
 * 數(shù)組說(shuō)明:該數(shù)組是一個(gè)二維數(shù)組,第一維索引代表班級(jí)編號(hào),第二維索引代表學(xué)生編號(hào)
 */
$CombinList = array(1 => array("Student10", "Student11"),
                    2 => array("Student20", "Student21", "Student22"),
                    3 => array("Student30"),
                    4 => array("Student40", "Student41", "Student42", "Student43"));
/* 計(jì)算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中的元素在拆分成組合后縱向出現(xiàn)的最大重復(fù)次數(shù)
    $RepeatTime = $RepeatTime / count($StudentList);
    $StartPosition = 1;
    // 開(kāi)始對(duì)每個(gè)班級(jí)的學(xué)生進(jìn)行循環(huán)
    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;
    }
}
/* 打印結(jié)果 */
echo "<pre>";
print_r($Result);
?>

相關(guān)文章

最新評(píng)論