How to generate all variations with repetitions of a string?
- by Svenstaro
I want to generate all variations with repetitions of a string in C++ and I'd highly prefer a non-recursive algorithm. I've come up with a recursive algorithm in the past but due to the complexity (r^n) I'd like to see an iterative approach.
I'm quite surprised that I wasn't able to find a solution to this problem anywhere on the web or on StackOverflow.
I've come up with a Python script that does what I want as well:
import itertools
variations = itertools.product('ab', repeat=4)
for variations in variations:
variation_string = ""
for letter in variations:
variation_string += letter
print variation_string
Output:
aaaa
aaab
aaba
aabb
abaa
abab
abba
abbb
baaa
baab
baba
babb
bbaa
bbab
bbba
bbbb
Ideally I'd like a C++ program that can produce the exact output, taking the exact same parameters.
This is for learning purposes, it isn't homework. I wish my homework was like that.