欢迎光临
我们一直在努力

计算排列组合的php代码-PHP教程,PHP应用

建站超值云服务器,限时71元/月

前些天因为业务需要写了一段计算排列组合的代码,今天整理了一下,以备后用

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

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » 计算排列组合的php代码-PHP教程,PHP应用
分享到: 更多 (0)