我试图取一个字符串并显示它的可能组合(在PHP中),但同时按每个单词的顺序说.例如:"你好吗"会返回(一个数组)
How are you
How are
are you
how
you
are
Run Code Online (Sandbox Code Playgroud)
我现在的代码显示了所有组合,但我希望它能保持顺序而不是翻转单词.任何人都有任何想要分享的想法或片段吗?谢谢
设置两个迭代器并在它们之间打印所有内容.所以像这样:
<?
$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";
}
}
?>
Run Code Online (Sandbox Code Playgroud)
产量
How
How are
How are you
are
are you
you
Run Code Online (Sandbox Code Playgroud)
我知道这是一篇非常旧的帖子,但另一个答案不是很灵活,所以我想我会带来一个新的答案。
\n\n因此,您正在寻找所有组合:
\n\n\n\n\n( 2n - 1
\n
在您的具体示例中将是:
\n\n\n\n\n(2 3 ) - 1 = (8) - 1 = 7
\n
那么我现在如何获得所有组合呢?我们循环遍历我们已经拥有的所有组合(从一个组合开始,一个“空组合”($results = [[]];)),对于每个组合,我们遍历数组中的下一个单词,并将每个组合与每个新单词组合成一个新组合。
例子
\n\nArray with the words/numbers (Empty array is \'[]\'):\n[1, 2, 3]\nRun Code Online (Sandbox Code Playgroud)\n\n\n\n
//\xe2\x86\x93new combinations for the next iteration\n \xe2\x94\x82\niteration 0:\n\n Combinations:\n - [] \xe2\x94\x82 -> []\n \xe2\x94\x82\niteration 1: \xe2\x94\x8c\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\xa4\n \xe2\x94\x82 \xe2\x94\x82\n Combinations: v v\n - [] + 1 \xe2\x94\x82 -> [1] \n \xe2\x94\x82\niteration 2: \xe2\x94\x8c\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\xa4\n \xe2\x94\x82 \xe2\x94\x82\n Combinations: v v\n - [] + 2 \xe2\x94\x82 -> [2]\n - [1] + 2 \xe2\x94\x82 -> [1,2] \n \xe2\x94\x82\niteration 3: \xe2\x94\x8c\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\xa4\n \xe2\x94\x82 \xe2\x94\x82\n Combinations: v v\n - [] + 3 \xe2\x94\x82 -> [3]\n - [1] + 3 \xe2\x94\x82 -> [1,3]\n - [2] + 3 \xe2\x94\x82 -> [2,3] \n - [1,2] + 3 \xe2\x94\x82 -> [1,2,3] \n //^ All combinations here\nRun Code Online (Sandbox Code Playgroud)\n\n正如您所看到的,总有:(2^n)-1组合。另外,从这个方法中,组合数组中还剩下一个空数组,因此在返回数组之前,我只是用来array_filter()删除所有空数组并array_values()重新索引整个数组。
<?php\n\n $str = "how are you";\n\n\n function getCombinations($array) {\n\n //initalize array\n $results = [[]];\n\n //get all combinations\n foreach ($array as $k => $element) {\n foreach ($results as $combination)\n $results[] = $combination + [$k => $element];\n }\n\n //return filtered array\n return array_values(array_filter($results));\n\n }\n\n\n $arr = getCombinations(explode(" ", $str));\n\n foreach($arr as $v)\n echo implode(" ", $v) . "<br />";\n\n\n?>\nRun Code Online (Sandbox Code Playgroud)\n\n输出:
\n\nhow\nare\nhow are\nyou\nhow you\nare you\nhow are you\nRun Code Online (Sandbox Code Playgroud)\n