n个单词的组合

时间:2014-02-06 12:04:58

标签: php algorithm

我有这段代码:

<?php

$str = "apple pear banana orange";
$str_splode = explode(' ',$str);
$combos = showCombo(array(), $str_splode);
foreach($combos as $key=>$array){
    echo $key.PHP_EOL;
    displayArrayByKey($key, $array);
}


function displayArrayByKey($str, $arr){
    foreach($arr as $key=>$array){
          $string = $str. " " . $key;
          echo $string . PHP_EOL; 
          if(count($array)> 0){
              displayArrayByKey($string, $array);
          }
    }
}

function showCombo($str_arr, $arr){
    $ret = array();
    foreach($arr as $val){
       if(!in_array($val, $str_arr)){
           $temp = $str_arr;
           $temp[] = $val;
           $ret[$val] = showCombo($temp, $arr);
       }
    }
    return $ret;
}

?>

它打印$ str var中的每个单词组合。 问题是我只想打印n个单词的组合(其中n是我的$ str var中的单词数,在这种情况下:4)。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

试试这个

function pc_permute($items, $perms = array()) {
    if (empty($items)) { 
        print join(' ', $perms) . "\n";
    }  else {
        for ($i = count($items) - 1; $i >= 0; --$i) {
             $newitems = $items;
             $newperms = $perms;
             list($foo) = array_splice($newitems, $i, 1);
             array_unshift($newperms, $foo);
             pc_permute($newitems, $newperms);
         }
    }
}

pc_permute(explode(" ", "apple pear banana orange"));

发现于:http://docstore.mik.ua/orelly/webprog/pcook/ch04_26.htm