php array combination

后端 未结 1 927
伪装坚强ぢ
伪装坚强ぢ 2021-01-23 23:31

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),         


        
相关标签:
1条回答
  • 2021-01-23 23:53

    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;
    }
    
    0 讨论(0)
提交回复
热议问题