views:

451

answers:

1

I want to generate all combination of length r from a set [0...(n-1)]

So the output should be like this (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));

with a function like

function permutate($select, $max)

where $select = r and $max = n

this is my current attempt but my brain doesnt seem to be functioning this evening and it only works for $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;
}

Thanks in advance

+3  A: 

Since you need an undefined number of loops, you will need to do it recursively:

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;
}
soulmerge
this only works for $select = 2, as when $select = 3 you only get array(array(0,1),array(0,2) ......) ;when it should bearray(array(0,1,2), array(0,2,3) ......)
lloydsparkes
Oh, now I get your idea! Fixing the answer ...
soulmerge
yes works perfectly thanks
lloydsparkes