首页 > 开发 > PHP > 正文

计算排列组合的php代码

2024-05-04 22:53:30
字体:
来源:转载
供稿:网友

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

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

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表