PHP的排列组合问题 分别从每一个集合中取出一个元素进行组合,问有多少种组合?

首先说明这是一个数学的排列组合问题
C(m,n) = m!/(n!*(m-n)!)

比如:有集合('粉色','红色','蓝色','黑色'),('38码','39码','40码'),('大号','中号') 分别从每一个集合中取出一个元素进行组合,问有多少种组合?
解:C(4,1) * C(3,1) * C(2,1) = (4!/(1!*(4-1)!)) * (3!/(1!*(3-1)!)) * (2!/(1!*(2-1)!))
= 24/6 * 6/2 * 2
= 4 * 3 * 2
= 24(种)

<?php
/*
首先说明这是一个数学的排列组合问题
C(m,n) = m!/(n!*(m-n)!)

比如:有集合('粉色','红色','蓝色','黑色'),('38码','39码','40码'),('大号','中号') 分别从每一个集合中取出一个元素进行组合,问有多少种组合?
解:C(4,1) * C(3,1) * C(2,1) = (4!/(1!*(4-1)!)) * (3!/(1!*(3-1)!)) * (2!/(1!*(2-1)!))
                             = 24/6 * 6/2 * 2
        = 4 * 3 * 2
        = 24(种)
 */

function combArray ($data)
{
    //首先计算出有多少种可能
    $counts = 1;
    foreach($data as $Key => $val)
        $counts *= count($val);

    $repeat_counts = $counts;

    //循环数据
    $result = array();
    foreach($data as $key => $val)
    {
        $tmp_count = count($val);
        $repeat_counts = $repeat_counts / $tmp_count;//计算出每组元素纵向有几种可能
        $start_pos = 1;
        foreach($val as $val1)
        {
            $temp_start_pos = $start_pos;
            $space_count = $counts / $tmp_count / $repeat_counts;
            for($i = 1; $i <= $space_count; $i ++)
            {
                for($j = 0; $j < $repeat_counts; $j ++)
                {
                    $result[$temp_start_pos + $j][$key] = $val1;
                }
                $temp_start_pos += $repeat_counts * $tmp_count;
            }
            $start_pos += $repeat_counts;
        }
    }
    return $result;
}


$data = array(
 array('粉色','红色'),
 array('38码','39码'),
 array('大号','中号'),
 array('长款','短款'),
);

$res = combArray($data);

header('Content-Type: text/html; charset=utf-8');
foreach ($res as $key => $val )
{
 echo implode(' ,',$val);echo '<br />';
}
echo '<pre>';
print_r ($res);
exit();

  

——在青春的路上,我们与你携手共进!
原文地址:https://www.cnblogs.com/sajanray/p/4478762.html