基于字符集的固定长度的所有字符串组合

发布于 2024-12-11 09:49:23 字数 182 浏览 6 评论 0原文

我正在创建一个函数,该函数将使用字符集返回给定字符串长度内的每个可能的字符串。

例如,字符集“abc”和长度 2 应允许 9 (3 ^ 2) 个唯一组合:

aa、 ab, 交流电, 巴, BB, 公元前, 加州, CB, cc

(手动构建的列表)

可以使用什么方法来创建这样的函数?

I'm looking to create a function that will return every possible string within a given string length, using a charset.

As an example, a charset of "abc", and a length of 2 should allow for 9 (3 ^ 2) unique combinations:

aa,
ab,
ac,
ba,
bb,
bc,
ca,
cb,
cc

(List constructed manually)

What method could be used to create such a function?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

无法回应 2024-12-18 09:49:23

与往常一样,有多种方法可以解决您的要求,这只是一种方法,在输出字符串中的每个字符使用一个计数器:

$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

一个主循环,一个循环构建字符串,一个循环用于计数。

我可以想象这也应该适用于获取输出字符串每个位置的模数。

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

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.

沦落红尘 2024-12-18 09:49:23

您已经做过了,我们可以从您的示例解决方案中清楚地看到:

aa, ab, ac, ba, bb, bc, ca, cb, cc

做了什么你在脑子里想出了这个解决方案吗?您必须记住一些事情:

  1. 我应该从字符集中开始的字符是什么?

  2. 当我构建输出字符串时,字符集中的下一个字符是什么?

  3. 我可以从字符集中选择多少个字符?

  4. 当我从字符集中选择了允许的所有字符时,我必须做什么?

  5. 对于我可以开始的字符,我是否已经用尽了字符集?如果是,我就完成了。

你能把它翻译成代码吗?还是这个答案太可爱了?

You already did go about this, as we can plainly see from your example solution:

aa, ab, ac, ba, bb, bc, ca, cb, cc

What did you do in your head to come up with this solution? You had to keep a few things in mind:

  1. what's the char I should start with from charset?

  2. as I am constructing the output string, what's the next char from charset?

  3. how many chars am I allowed to pick from charset?

  4. what must I do when I've picked from charset all the chars that I'm allowed to?

  5. have I exhausted charset with respect to chars I can start with? if yes, I'm finished.

Can you translate this into code? Or is this answer just too cutesy?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文