显示字符串的可能组合
我试图获取一个字符串并显示它的可能组合(在 PHP 中),但同时按每个单词的顺序说出。例如:“你好吗”将返回(一个数组)
How are you
How are
are you
how
you
are
我现在的代码显示所有组合,但我希望它保持它们的顺序而不是翻转单词。有人有任何想法或片段愿意分享吗?谢谢
I am trying to take a string and display the possible combinations of it (in PHP), but while saying in order of each word. For example: "how are you" would return (an array)
How are you
How are
are you
how
you
are
The code I have now displays all combinations but I am wanting it to keep them in order and not flip words. Any one have any ideas or snippets they care to share? Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
设置两个迭代器并打印它们之间的所有内容。所以像这样:
输出
Set two iterators and print everything between them. So something like this:
Output
我知道这是一篇非常旧的帖子,但另一个答案不是很灵活,所以我想我会带来一个新的答案。
解释
所以你正在寻找所有组合:
在您的具体示例中将是:
那么我现在如何获得所有组合呢?我们循环遍历我们已经拥有的所有组合(从一个组合开始,一个“空组合”(
$results = [[]];
)),对于每个组合,我们都会遍历我们的数组中的下一个单词,并将每个组合与每个新单词组合成一个新组合。示例
正如您所看到的,总共有:
(2^n)-1
组合。另外,从这个方法中,组合数组中留下了一个空数组,因此在返回数组之前,我只使用array_filter()
删除所有空数组和array_values()
重新索引整个数组。代码
输出:
I know this is a very old post, but the other answer isn't very flexible, so I thought I would bring a new answer in.
Explanation
So you are looking for all combinations which would be:
Which in your specific example would be:
So how do I get all combinations now? We loop through all our combinations, which we already have(Starting off with one combination, an "empty combination" (
$results = [[]];
)), and for each combination we go through our next word from the array and combine each combination with each new word to a new combination.Example
So as you can see there is always:
(2^n)-1
combinations in total. Also from this method there is an empty array left in the combination array, so before I return the array I just usearray_filter()
to remove all empty arrays andarray_values()
to reindex the entire array.Code
output:
回答问题不带缺货订单的 PHP 数组组合。在那里,有必要获得数组元素的所有可能组合并存储以下内容。
结果示例此处
Answer for question PHP array combination with out back order. There it was necessary to obtain all possible combinations of array elements and store the following.
Example result here