PHP数组收集
我有 24 个字符的字母数组:“ABCDEFGHIJKLMNOPQRSTU VW X”
我想收集所有带有以下内容的案例:3 个唯一字符。
第一种情况:ABC、DEF、GHI、JKL、MNO、PQR、STU、VWX
I have alphabet array 24 character: "A B C D E F G H I J K L M N O P Q R S T U V W X"
I want collect all case with: 3 unique characters.
First case: ABC, DEF, GHI, JKL, MNO, PQR, STU, VWX
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这有点晚了,但对于阅读本文的其他人来说:如果您希望将字符串拆分为 3 个字符的块,请尝试 PHP 内置的 str_split() 函数。它接受
$string
和$split_length
参数。例如:这输出以下数组:
这适用于问题中给出的示例。如果你想要这 24 个字母的所有可能组合,Artefacto 的答案更有意义。
This is a little late coming, but for anyone else reading over this: If you are looking to split a string into 3-character chunks, try PHP's built in str_split() function. It takes in a
$string
and$split_length
argument. For example:This outputs the following array:
This works for the example given in the question. If you want to have every possible combination of those 24 letters, Artefacto's answer makes more sense.
字母表字母的排列与集合列表之间存在 1:1 的关系。基本上,一旦你有了字母表的排列,你只需调用 array_chunk 来获取集合。
现在,24!任何东西(即 620448401733239439360000)永远不会适合内存(无论是 RAM 还是磁盘),因此您能做的最好的事情就是生成
1
和1
之间的数字n
code>24! (排列数),然后生成这样的排列。对于最后一步,请参阅示例 遵循 Lehmer 和 Howell 的排列的生成 以及那里引用的论文。There's a 1:1 relationship between the permutations of the letters of the alphabet and your sets lists. Basically, once you have a permutation of the alphabet, you just have to call
array_chunk
to get the sets.Now, 24! of anything (that is 620448401733239439360000) will never fit in memory (be it RAM or disk), so the best you can do is to generate a number
n
between1
and24!
(the permutation number) and then generate such permutation. For this last step, see for example Generation of permutations following Lehmer and Howell and the papers there cited.希望我正确理解你的问题。该循环分三个循环迭代字母表,并始终跳过已使用的字符。然后我将结果推送到 $result。
但最好尝试只包含五个字母的脚本;)使用 alls strlen($alphabet) (现在不想数......)将需要大量内存。
(我确信有一些 hacky 版本比这更快,但我认为这是最简单的。)
Hope I understood your question right. This one iterates over the alphabet in three loops and always skips the characters which are already used. Then I push the result to $result.
But better try the script with only five letters ;) Using alls strlen($alphabet) (don't wanna count now...) will need incredibly much memory.
(I am sure there is some hacky version which is faster than that, but this is most straightforward I think.)