繁体   English   中英

php数组组合

[英]php array combination

我想从集合[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;
}

提前致谢

由于您需要一个未定义的循环数,因此您需要以递归方式执行此操作:

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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM