zoukankan      html  css  js  c++  java
  • 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();
    

      

    ——在青春的路上,我们与你携手共进!
  • 相关阅读:
    jquery的动画函数animate()讲解一
    用js来实现页面的换肤功能(带cookie记忆)
    Extjs换肤+cookie皮肤记忆功能
    jquery换肤
    bootstrap的alert提示框的关闭后再显示问题
    jquery.cookie中的操作
    CSS中设置margin:0 auto; 水平居中无效的原因分析
    jQuery 遍历 json 方法大全
    jquery.min.map 404 (Not Found)出错的原因及解决办法
    AJAX 跨域请求的解决办法:使用 JSONP获取JSON数据
  • 原文地址:https://www.cnblogs.com/sajanray/p/4478762.html
Copyright © 2011-2022 走看看