显示字符串的可能组合

时间:2010-07-08 02:14:01

标签: php combinations

我正在尝试取一个字符串并显示它的可能组合(在PHP中),但是按照每个单词的顺序说。例如:“你好吗”将返回(数组)

How are you
How are
are you
how
you
are

我现在的代码显示了所有组合,但我希望它能保持整齐,而不是翻转单词。任何人都有任何想要分享的想法或片段吗?感谢

3 个答案:

答案 0 :(得分:5)

设置两个迭代器并在它们之间打印所有内容。所以像这样:

<?
$str = "How are you";
$words = explode(" ",$str);
$num_words = count($words);
for ($i = 0; $i < $num_words; $i++) {
  for ($j = $i; $j < $num_words; $j++) {
    for ($k = $i; $k <= $j; $k++) {
       print $words[$k] . " ";
    }
    print "\n";
  }
}
?>

输出


How 
How are 
How are you 
are 
are you 
you 

答案 1 :(得分:2)

我知道这是一个非常古老的帖子,但另一个答案不是很灵活,所以我想我会带来一个新答案。


解释

所以你正在寻找所有的组合:

  

(2 n ) - 1

在您的具体示例中将是:

  

(2 3 ) - 1 =(8)-1 = 7

那么我现在如何获得所有组合?我们循环遍历我们已经拥有的所有组合(从一个组合开始,一个“空组合”($results = [[]];)),对于每个组合,我们通过数组中的下一个单词并将每个组合与新单词的每个新单词。

示例

Array with the words/numbers (Empty array is '[]'):
[1, 2, 3]

                               //↓new combinations for the next iteration
                               │
iteration 0:

    Combinations:
                  - []         │  -> []
                                  │
iteration 1:        ┌─────────────┤
                    │             │
    Combinations:   v             v
                  - []    + 1  │  -> [1]    
                                  │
iteration 2:        ┌─────────────┤
                    │             │
    Combinations:   v             v
                  - []    + 2  │  -> [2]
                  - [1]   + 2  │  -> [1,2]    
                                  │
iteration 3:        ┌─────────────┤
                    │             │
    Combinations:   v             v
                  - []    + 3  │  -> [3]
                  - [1]   + 3  │  -> [1,3]
                  - [2]   + 3  │  -> [2,3]         
                  - [1,2] + 3  │  -> [1,2,3]    
                               //^ All combinations here

因此,您可以看到总共有(2^n)-1个组合。此外,在这个方法中,组合数组中还有一个空数组,因此在返回数组之前,我只需使用array_filter()删除所有空数组,并使用array_values()重新索引整个数组。

代码

<?php

    $str = "how are you";


    function getCombinations($array) {

        //initalize array
        $results = [[]];

        //get all combinations
        foreach ($array as $k => $element) {
            foreach ($results as $combination)
                $results[] =  $combination + [$k => $element];
        }

        //return filtered array
        return array_values(array_filter($results));

    }


    $arr = getCombinations(explode(" ", $str));

    foreach($arr as $v)
        echo implode(" ", $v) . "<br />";


?>

输出:

how
are
how are
you
how you
are you
how are you

答案 2 :(得分:1)

回答问题PHP array combination with out back order。在那里,有必要获得所有可能的数组元素组合并存储以下内容。

<?php

$alphabet = array('a','b','c');
$result = array();
$arrResult = array();

// recursively create all possible combinations {
combine($alphabet, $result, $arrResult);

function combine($shiftedAlphabet, &$result, &$arrResult) {
    global $alphabet;

    $currentElementStr = '';
    $currentElementArr = array();
    for($i = 0; $i < count($shiftedAlphabet); ++$i) {
        $newElement = $shiftedAlphabet[$i];
        $currentElementStr .= $newElement;
        $currentElementArr[] = $newElement;

        if(!in_array($currentElementStr, $result)) { // if not duplicated => push it to result
            // find right position {
            $thisCount = count($currentElementArr);
            $indexFrom = 0;
            $indexToInsert = 0;

            // find range of indexes with current count of elements {
            foreach ($arrResult as $arrResultKey => $arrResultValue) {
                $indexToInsert = $arrResultKey + 1;
                if ($thisCount > count($arrResultValue)) {
                    $indexFrom = $indexToInsert;
                }
                if ($thisCount < count($arrResultValue)) {
                    --$indexToInsert;
                    break;
                }
            }
            // find range of indexes with current count of elements }

            // find true index inside true range {
            $trueIndex = $indexToInsert;
            $break = false;
            for($j = $indexFrom; $j < $indexToInsert; ++$j) {
                $trueIndex = $j + 1;
                foreach($arrResult[$j] as $key => $value) {
                    if (array_search($value, $alphabet) > array_search($currentElementArr[$key], $alphabet)) {
                        $break = true;
                        break;
                    }
                }
                if($break) {
                    --$trueIndex;
                    break;
                }
            }
            // find true index inside true range }

            array_splice($result, $trueIndex, 0, $currentElementStr);
            array_splice($arrResult, $trueIndex, 0, array($currentElementArr));
        }
    }

    for($i = 0; $i < count($shiftedAlphabet) - 1; ++$i) {
        $tmpShiftedAlphabet = $shiftedAlphabet; // for combining all possible subcombinations
        array_splice($tmpShiftedAlphabet, $i, 1);
        combine($tmpShiftedAlphabet, $result, $arrResult);
    }
}
// recursively create all possible combinations }
var_dump($result); 

?>

示例结果here