获取所有非重复的字符串组合(无论顺序如何)


get all non repetitive combinations of strings (no matter the order)

php:给定一个非重复字符串列表,如

  $strings=array("asd","qwerty","123");// or more 

我想要像一样的所有非重复组合(无论订单如何(

  asd       
  asd   qwerty  
  asd   123 
  asd   qwerty  123
  qwerty        
  qwerty    123 
  123       

我正在寻找最有效的算法,并在一个单一的函数

主要思想是组合的数量(如果所有字符串都不同(是n^2-1,其中n=字符串数。因此,我们可以使用第i个组合的二进制表示来构建我们唯一的组合。

在代码中,它看起来是这样的:

$someArray = ['abc', 'def', 'foo', 'bar'];
$combinations = pow(2, count($someArray)) - 1;
$result = [];
for ($i = 0; $i < $combinations; $i++) {
    $result[$i] = [];
    for ($j = 0; $j < count($someArray); $j++) {
       // here we check if j-th bit of i is equal to 1
       if (($i >> $j) & 1 == 1) {
           $result[$i][] = $someArray[$j];
       }
    }
}

不是尝试最快的解决方案,而是从一个解决方案开始,请尝试一下:

$strings=array("asd","qwerty","123");// or more 
$sortstrings=natsort(array_unique($strings)); // sort and remove duplicates 
$new_arr=array();
foreach ($strings as $str)
{
   foreach($new_arr as $new)
   {
      $newstr="$new$str";
      if (!in_array("$newstr",$new_arr))
         $new_arr[]="$newstr";
   }   
   if (!in_array("$str",$new_arr))
      $new_arr[]="$str";
}