• 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();
    

      

    ——在青春的路上,我们与你携手共进!
  • 相关阅读:
    css注入获取网页中的数据
    跨路径读取cookie
    python 网络爬虫介绍
    ssh无法登录,提示Connection closing...Socket close.
    Tengine 添加第三方监控模块nginx-module-vts
    使用nginx很卡之strace命令
    MySQL清理慢查询日志slow_log的方法
    Python之json模块
    zabbix3调用接口发送短信告警
    RabbitMQ 安装 rabbitmq_delayed_message_exchange插件
  • 原文地址:https://www.cnblogs.com/sajanray/p/4478762.html
Copyright © 2020-2023  润新知