基于字符集的固定长度的所有字符串组合 [英] all string combinations in a fixed length, based on a charset
问题描述
我正在寻求创建一个函数,该函数将使用字符集返回给定字符串长度内的所有可能字符串.
I'm looking to create a function that will return every possible string within a given string length, using a charset.
例如,一个字符集"abc",长度为2,应允许9(3 ^ 2)个唯一组合:
As an example, a charset of "abc", and a length of 2 should allow for 9 (3 ^ 2) unique combinations:
aa, ab, 交流电 爸 bb, 公元前, ca cb, cc
aa, ab, ac, ba, bb, bc, ca, cb, cc
(手动构建的列表)
可以使用什么方法来创建这样的功能?
What method could be used to create such a function?
推荐答案
和往常一样,有多种方法可以解决您的要求,这只是一种方法,在输出字符串中每个字符使用一个计数器:
As always, there are multiple ways to solve what you ask for, this is only one way, using one counter per character in the output string:
$c = "abc"; // charset
$l = 2; // string length
for($t='',$cl=strlen($c),$s=array_fill(0,$l,0),$i=pow($cl,$l);$a=0,$i--;) {
for($t&&$t.=', ';$a<$l;$t.=$c[$s[$a++]]);
for(;$a--&&++$s[$a]==$cl;$s[$a]=0);
};
echo $t; // the string you asked for.
aa,ab,ac,ba,bb,bc,ca,cb,cc
aa, ab, ac, ba, bb, bc, ca, cb, cc
一个主循环,一个用于构建字符串的循环和一个用于计数的循环.
One main loop, one loop to build the string and one loop for counting up.
我可以想象这应该也可以在输出字符串的每个位置获取模数.
I can imagine this should work with getting modulos per each position of the output string as well.
这篇关于基于字符集的固定长度的所有字符串组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!