I’m trying to write a recursive function that gets all permutations with repetitions of a given list.
Eg. set = ABC
1. AAA
2. AAB
3. AAC
4. ABA
N. CCC
I want a recursive version of this code so I can get permutations for sets of any size:
for i=0; i<S.size(); i++ {
for j=0; j<S.size(); j++ {
for k=0; k<S.size(); k++ {
perm[0] = S[i];
perm[1] = S[j];
perm[2] = S[k];
permutations.push(combo);
}
}
}
I’m having some trouble wrapping my head around the problem. So far I’m thinking I need to find when I’ve reached an arbitrary depth to stop re-cursing.
Edit: I’d prefer a pseudo-code solution, I’m not implementing this in C++
I think an iterative solution will be more efficient, and it can be written to support arbitrary dimensions and numbers of symbols. The code is in C++, but I delibaretely kept it simple so that you can easily translate into pseudocode or other language:
The output should be:
If you want the symbols in the last position to change fastest, just reverse the contents of each row of the generated output.
Of course, you can make
generate_combinationsa template function and make it work with other types thanchar.============ UPDATE =================
A recursive solution is, of course, more elegant:
Use it in place of
generate_combinationsfunction in the first program. It should give you the same output as before.