0

I can't wrap my head around the algorithm for making the following:

I have an array for all possible characters: array("a", "b", "c",...."z", " ", "!"...) you get the idea.

Now I would like to generate all possible compinations of these characters with the length of x.

so for example the array("a", "b", "c") with the length of 4: aaaa abaa acaa aaba aaca aaab aaac abba abca acba acca (....) baaa caaa

and so on...

Thanks in advice!

3Descape
  • 5
  • 1
  • I believe those are technically "*permutations*" rather than combinations. https://www.mathsisfun.com/combinatorics/combinations-permutations.html – RBarryYoung May 19 '16 at 15:23

1 Answers1

0

You can try it with recursion:

COMBINATIONS(array, length):
    COMBINATIONS("", array, length)

COMBINATIONS(string, array, length):
    IF length == 0
        VISIT(string)
    ELSE
        FOR EACH c IN array
            COMBINATIONS(string + c, array, length - 1)

The basic idea is start with an empty string, then in each execution, call recursively for each character in the array. This will generate for each string previously generated a new string for each character in the array concatenated at the end.

When you reach the desired length then 'visit' the generated combination.

For example, for array = ['a', 'b', 'c'] and length = 3:

aaa
aab
aac
aba
abb
abc
aca
acb
acc
baa
bab
bac
bba
bbb
bbc
bca
bcb
bcc
caa
cab
cac
cba
cbb
cbc
cca
ccb
ccc
Arturo Menchaca
  • 15,783
  • 1
  • 29
  • 53