Chinaunix首页 | 论坛 | 博客
  • 博客访问: 17767636
  • 博文数量: 7460
  • 博客积分: 10434
  • 博客等级: 上将
  • 技术积分: 78178
  • 用 户 组: 普通用户
  • 注册时间: 2008-03-02 22:54
文章分类

全部博文(7460)

文章存档

2011年(1)

2009年(669)

2008年(6790)

分类:

2008-05-17 11:08:04

一段计算排列组合的

/**
 * 要解决的数学问题    :算出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 "

";
print_r($Result);
?>

阅读(330) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~