Generate all possible combinations using a set of strings

前端 未结 4 1197
小鲜肉
小鲜肉 2020-12-16 08:17

I\'m trying to generate all possible combinations of a set of strings, using each string maximum once.

  • The length of the output string isn\'t defined (the max
4条回答
  •  情话喂你
    2020-12-16 08:52

    Here is my implementation which I have written for quite some time using basic mathematical definiton of combination and permutation. Maybe this could help.

     2 ) {
                $tmp = permute($array);
            }
            elseif(count($array) == 2) {
                $array_ = $array;
                krsort($array_);
                $tmp = array($array, $array_);
            }
            elseif(count($array) == 1) {
                $tmp = array($array);
            }
            elseif(count($array) == 0) {
                $tmp = array(array());
            }
    
            foreach($tmp as $k => $t) {
                array_unshift($t, $first);
                $tmp[$k] = $t;
            }
    
            $results = array_merge($results, $tmp);
    
            array_push($array, $first);
        }
    
        return $results;
    }
    
    $strings = array('T', 'O', 'RS');
    $strings_count = count($strings);
    
    
    $combinations = array();
    for ($i = 1; $i <= $strings_count; $i++) {
      $combination = combine($strings, $i, 0);
      $combinations = array_merge($combinations, $combination);
    }
    
    $permutations = array();
    foreach($combinations as $combination) {
      $permutation = permute($combination);
      $permutations = array_merge($permutations, $permutation);
    }
    
    print_r($combinations);
    print_r($permutations);
    

提交回复
热议问题