【问题标题】:php array combinationphp数组组合
【发布时间】:2010-11-28 23:08:43
【问题描述】:

我想从一组 [0...(n-1)] 中生成所有长度为 r 的组合

所以输出应该是这样的(n = 6 r = 2)

$res = array(array(0,1),array(0,2),array(0,3),array(0,4),array(0,5),array(1,2),array(1,3),array(1,4),array(1,5),array(2,3),array(2,4),array(2,5),array(3,4),array(3,5),array(4,5));

具有类似的功能

function permutate($select, $max)

其中 $select = r 和 $max = n

这是我目前的尝试,但我的大脑今晚似乎无法正常工作,它仅适用于 $select = 2

function permutate($select, $max)
{
    $out = array();
    for( $i = 0; $i < ($max) ; $i++)
    {
        for ($x = ($i + 1); $x < ($max); $x++)
        {

            $temp = array($i);

            for($l = 0; $l < ($select-1); $l++)
            {
                if(($x+$l) < $max )
                {                
                    array_push($temp, $x+$l);
                }
            }    
            if(count($temp) == $select)
            {
                array_push($out, $temp);
            }
        }
    }

    return $out;
}

提前致谢

【问题讨论】:

    标签: php combinations


    【解决方案1】:

    由于您需要未定义数量的循环,因此您需要递归执行:

    function permutation($select, $max) {
        if ($select === 1) {
            $result = range(0, $max);
            foreach ($result as &$entry) {
                $entry = array($entry);
            }
            return $result;
        }
        $result = array();
        $previous = permutation($select - 1, $max - 1);
        foreach ($previous as $entry) {
            $last = end($entry);
            for ($i = $last + 1; $i <= $max; $i++) {
                $result[] = array_merge($entry, array($i));
            }
        }
        return $result;
    }
    

    【讨论】:

    • 这只适用于 $select = 2,因为当 $select = 3 你只得到 array(array(0,1),array(0,2) ......) ;什么时候应该是array(array(0,1,2), array(0,2,3) ......)
    猜你喜欢
    • 2011-04-14
    • 2010-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多