I am trying to deduce an algorithm which generates all possible combinations of a specific size something like a function which accepts an array of chars and size as its parameter and return an array of combinations.
Example: Let say we have a set of chars: Set A = {A,B,C}
a) All possible combinations of size 2: (3^2 = 9)
AA, AB, AC
BA, BB, BC
CA, CB, CC
b) All possible combinations of size 3: (3^3 = 27)
AAA, AAB, AAC,
ABA, ABB, ACC,
CAA, BAA, BAC,
.... ad so on total combinations = 27
Please note that the pair size can be greater than total size of pouplation. Ex. if set contains 3 characters then we can also create combination of size 4.
EDIT: Also note that this is different from permutation. In permutation we cannot have repeating characters for example AA cannot come if we use permutation algorithm. In statistics it is known as sampling.
I would use a recursive function. Here's a (working) example with comments. Hope this works for you!
You can do this recursively. Note that as per your definition, the "combinations" of length
n+1
can be generated from the combinations of lengthn
by taking each combination of lengthn
and appending one of the letters from your set. If you care you can prove this by mathematical induction.So for example with a set of
{A,B,C}
the combinations of length 1 are:The combinations of length 2 are therefore
This would be the code and here on ideone
A possible algorithm would be:
Basically, what you will do is take each element of the current set and append all the elements of the element array.
In the first step: you will have as result
('a', 'b', 'c')
, after the seconds step:('aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc')
and so on.