Marwelln
Marwelln

Reputation: 29413

How many unique strings is possible with set amount of characters and length?

If I have two characters (a, b) and a length of three (aaa, aab ...), how do I count how many unique strings I can make of that (and what is the math method called)?

Is this correct?

val = 1, amountCharacters = 2, length = 3;
for (i = 1; i <= length; ++i) { val = amountCharacters*val; uniqueStrings = val }

This example returns 8 which is correct. If I try with something higher, like amountCharacters = 10 it returns 1000. Is it still correct?

Upvotes: 6

Views: 8933

Answers (3)

templatetypedef
templatetypedef

Reputation: 372814

If you have n different characters and the length is k, there are exactlty nk possible strings you can form. Each character independently of the rest can be one of n different options and there are k total choices to make. Your code is correct.

For 2 possible characters and 10 letters, there are exactly 1024 possible strings.

Hope this helps!

Upvotes: 11

David Cummins
David Cummins

Reputation: 988

If I understand your question correctly, if you have N characters and want to construct a string of length L, the number of combinations is just N^L (e.g. N to the power of L).

There are various other results you can get if there are different limitations on what the string can contain, e.g. combinations or permutations.

Upvotes: 2

Steve B
Steve B

Reputation: 37660

The same rules than Base mathematics concept applies.

So the short answer is amountCharacters ^ length.

Longest natural answer.

  • The first letter will have X possible values
  • The second letter will have X*X possible values
  • and so on ..
  • X equals the number of possible values, i-e the amount of characters in your question

Upvotes: 2

Related Questions