PHP Find All (somewhat) Unique Combinations of an Array

后端 未结 6 2213
独厮守ぢ
独厮守ぢ 2020-12-03 12:02

I\'ve been looking at PHP array permutation / combination questions all day.. and still can\'t figure it out :/

If I have an array like:

20 //key bei         


        
6条回答
  •  青春惊慌失措
    2020-12-03 12:43

    The pear package Math_Combinatorics makes this kind of problem fairly easy. It takes relatively little code, it's simple and straightforward, and it's pretty easy to read.

    $ cat code/php/test.php
    combinations($input, 3);
    for ($i = 0; $i < count($combinations); $i++) {
      $vals = array_values($combinations[$i]);
      $s = implode($vals, ", ");
      print $s . "\n";
    }
    ?>
    
    $ php code/php/test.php
    20, 20, 22
    20, 20, 24
    20, 22, 24
    20, 22, 24
    

    If I had to package this as a function, I'd do something like this.

    function combinations($arr, $num_at_a_time) 
    {
        include_once 'Math/Combinatorics.php';
    
        if (count($arr) < $num_at_a_time) {
            $arr_count = count($arr);
            trigger_error(
                "Cannot take $arr_count elements $num_at_a_time " 
                ."at a time.", E_USER_ERROR
            );
        }
    
        $c = new Math_Combinatorics;
        $combinations = $c->combinations($arr, $num_at_a_time);
    
        $return = array();
        for ($i = 0; $i < count($combinations); $i++) {
            $values = array_values($combinations[$i]);
            $return[$i] = $values;
        }
        return $return;
    }
    

    That will return an array of arrays. To get the text . . .

    
    20, 20, 22
    20, 20, 24
    20, 22, 24
    20, 22, 24
    

提交回复
热议问题