How to generate all variations with repetitions of a string?
Posted
by Svenstaro
on Stack Overflow
See other posts from Stack Overflow
or by Svenstaro
Published on 2010-06-11T21:08:24Z
Indexed on
2010/06/11
21:12 UTC
Read the original article
Hit count: 392
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.
© Stack Overflow or respective owner