Reputation: 29413
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
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
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
Reputation: 37660
The same rules than Base mathematics concept applies.
So the short answer is amountCharacters ^ length
.
Longest natural answer.
Upvotes: 2