开发者

permutation/generate combination prefix and suffix

I have an array of prefixes, an array of base words and an array of suffixes. I would like to see every combination that can be made.

Example:

   pr开发者_如何学编程efixes: 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

How can I do this?

Edit: Thanks for all the responses, I am going through the solutions but it seems like if there are no prefixes, then it will fail for combination. It should still go through the base words and suffixes, even without any prefixes.


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


for each $prefix in $prefixes {
for each $base in $basewords {
for each $suffix in $suffixes {
echo $prefix.$base.$suffix."\n"
}}}

This will do what you want, I believe there is no builtin function to do this in php (Though there is in python)


this should get you started:

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

result:
1hello_x
1hello_y
1test_x
1test_y
2hello_x
2hello_y
2test_x
2test_y

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜