【问题标题】:permutation/generate combination prefix and suffix排列/生成组合前缀和后缀
【发布时间】:2011-03-06 21:29:19
【问题描述】:

我有一个前缀数组、一个基词数组和一个后缀数组。我想看看可以做出的每一种组合。

例子:

   prefixes: 1 2
    words: hello test
    suffixes: _x _y

   Results:

1hello_x 
1hello_y 
1hello   
1test_x  
1test_y  
1test    
1_x      
1_y      
1        
2hello_x 
2hello_y
2hello  
2test_x 
2test_y 
2test   
2_x     
2_y     
2       
hello_x 
hello_y 
hello   
test_x  
test_y  
test    
_x      
_y      
y

我该怎么做?

编辑:感谢所有回复,我正在研究解决方案,但似乎如果没有前缀,那么组合将失败。即使没有任何前缀,它仍应通过基本词和后缀。

【问题讨论】:

    标签: php arrays combinations permutation


    【解决方案1】:
    function combineAll ($prefixes, $words, $suffixes)
    {
      $combinations = array ();
      foreach ($prefixes as $prefix)
      {
        foreach ($words as $word)
        {
          foreach ($suffixes as $suffix)
          {
             $combinations[] = $prefix.$word.$suffix;
          }
        }
      }
      return $combinations;
    }
    

    【讨论】:

    • 如果我只添加array_push($prefixes, ""); .. array_push($words, ""); array_push($prefixes, ""); 那么它将满足我的需要。另请注意,您在参数中有 $suffixed,而不是后缀
    • 叹气,请首先发布“完整”问题,而不是多次更改。
    【解决方案2】:
    for each $prefix in $prefixes {
    for each $base in $basewords {
    for each $suffix in $suffixes {
    echo $prefix.$base.$suffix."\n"
    }}}
    

    这会做你想做的,我相信在 php 中没有内置函数可以做到这一点(虽然在 python 中有)

    【讨论】:

      【解决方案3】:

      这应该让你开始:

      http://ask.amoeba.co.in/php-combinations-of-array-elements/

      //$a = array("1", "2");
      $b = array("hello", "test");
      $c = array("_x", "_y");
      
      if(is_array($a)){
      $aG = array($a,$b, $c);
      }else{
      $aG = array($b, $c);
          }
      $codes = array();
      $pos = 0;
      generateCodes($aG);
      
      function generateCodes($arr) {
          global $codes, $pos;
          if(count($arr)) {
              for($i=0; $i<count($arr[0]); $i++) {
                  $tmp = $arr;
                  $codes[$pos] = $arr[0][$i];
                  $tarr = array_shift($tmp);
                  $pos++;
                  generateCodes($tmp);
      
              }
          } else {
              echo join("", $codes)."<br/>";
          }
          $pos--;
      }
      

      结果:
      1hello_x
      1hello_y
      1test_x
      1test_y
      2hello_x
      2hello_y
      2test_x
      2test_y

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-04-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-27
        • 2013-12-20
        • 1970-01-01
        相关资源
        最近更新 更多