Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

php - 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.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...