Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
217 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 Answer

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...