基于字符集的固定长度的所有字符串组合
我正在创建一个函数,该函数将使用字符集返回给定字符串长度内的每个可能的字符串。
例如,字符集“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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
与往常一样,有多种方法可以解决您的要求,这只是一种方法,在输出字符串中的每个字符使用一个计数器:
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:
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.
您已经做过了,我们可以从您的示例解决方案中清楚地看到:
aa, ab, ac, ba, bb, bc, ca, cb, cc
做了什么你在脑子里想出了这个解决方案吗?您必须记住一些事情:
我应该从字符集中开始的字符是什么?
当我构建输出字符串时,字符集中的下一个字符是什么?
我可以从字符集中选择多少个字符?
当我从字符集中选择了允许的所有字符时,我必须做什么?
对于我可以开始的字符,我是否已经用尽了字符集?如果是,我就完成了。
你能把它翻译成代码吗?还是这个答案太可爱了?
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:
what's the char I should start with from charset?
as I am constructing the output string, what's the next char from charset?
how many chars am I allowed to pick from charset?
what must I do when I've picked from charset all the chars that I'm allowed to?
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?