如何获得单词字符的所有唯一组合?
我了解 str_shuffle()
或 shuffle 的工作原理,但在这种情况下我不知道。
$word="tea";
我想回显所有独特的洗牌可能性(tea、tae、eta、eat、ate、aet)
I understand how str_shuffle()
or shuffle works but I don't know it in this case.
$word="tea";
I want to echo out all unique shuffling possibilities (tea, tae, eta, eat, ate, aet)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要通过迭代可能性或使用如下所示的递归方法来生成字符串的所有排列。请注意,对于中等大小的数组,这会很快变得非常大。对于具有唯一字符的单词,可能的排列数为n!其中 n 是长度。对于 6 个字母的单词,数组将有 720 个条目!这种方法不是最有效的,但根据您想要做什么,它应该可以正常工作。
(来源:http://cogo.wordpress.com/2008 /01/08/string-permutation-in-php/)
请注意,这种有点幼稚的实现将无法正确处理重复的字母(例如,“seed”,有两个 e)。如上面的源所示,如果单词包含多个相同字母,您可以使用以下代码来消除重复:
You need to produce all of the permutations of the string, either by iterating through the possibilities, or using a recursive method like this one below. Note that for a moderately sized array this will grow very large very quickly. For a word with unique characters, the number of possible permutations is n! where n is the length. For a six-letter word the array will have 720 entries! This method is not the most efficient, but depending on what you are trying to do, it should work ok.
(Source: http://cogo.wordpress.com/2008/01/08/string-permutation-in-php/)
Note that this somewhat naive implementation will not handle duplicate letters correctly (for example, 'seed', having two e`s). As indicated in the source above, you can use the following code to eliminate duplicates if the word contains multiple of the same letter: