【问题标题】:php - get all non repetitive combinations of strings (no matter the order)php - 获取所有不重复的字符串组合(无论顺序)
【发布时间】:2016-10-27 21:19:08
【问题描述】:

php: 给定一个不重复的字符串列表,例如

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

我想获得所有不重复的组合(无论顺序如何),例如

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

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

【问题讨论】:

  • 列表是数组还是单独的变量?
  • 列表总是像array("str1","str2","str3","str4","str5",...)这样的数组
  • 只是澄清一下——当你说非重复......无论顺序如何,你的意思是相同的值以不同的顺序是重复的——所以跳过?
  • 准确,但我不想简单地“跳过”它们,而是不要循环它们(“避免”)
  • Miky,到目前为止你尝试过什么?

标签: php string algorithm combinations


【解决方案1】:

主要思想是组合数(如果所有字符串都不同)为 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];
       }
    }
}

【讨论】:

  • 接近完美!它只有一个“”值更多,而不是“所有字符串”值
  • 我做错了。可以通过 for ($i = 1; $i 轻松修复
【解决方案2】:

不尝试最快,但只是从解决方案开始,试试这个:

$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";
}

【讨论】:

  • 我想你忘了!在 if 语句中,但无论如何我只得到“asd,qwerty,123”
猜你喜欢
  • 2012-08-16
  • 1970-01-01
  • 2010-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-22
  • 1970-01-01
相关资源
最近更新 更多