I need to generate all possible permutations of p
different characters, at length r
with repeated characters in the string. I have an additional constraint- I can only have n
consecutive repeated characters at any point within each permutation.
Constraints:
(1 ≤ p, r, n ≤ 12)
For example: For the letters "AB", with an r value of 4 and an n value of 2 I'd like the following output:
AABA
AABB
ABAA
ABAB
ABBA
BAAB
BABA
BABB
BBAA
BBAB
The maximum number of adjacent identical characters, n, is 2.
I've achieved the desired output by finding the cartesian product of the string, then iterating through the results and eliminating any that don't fit the n value. My approach is incredibly slow though! Here's my code, if needed:
s = "AB"
q = 2
r = 4
pools = [s] * r
result = [[]]
final = []
for pool in pools:
result = [x+[y] for x in result for y in pool]
check = [''.join([l]*(q+1))for l in s]
for r in result:
add = True
z = ''.join(r)
for c in check:
if c in z:
add = False
break
if add:
final.append(z)
print(final)
# ['AABA', 'AABB', 'ABAA', 'ABAB', 'ABBA', 'BAAB', 'BABA', 'BABB', 'BBAA', 'BBAB']
My solution works for the input above, but for larger numbers/string it takes multiple minutes. For example, the following inputs would take a long time using my solution:
s = "ABCDEF"
q = 3
r = 10
I'd like a solution that would preferably take less than a second. I wrote a much faster recursive solution, but that crashed my machine with memory errors for larger numbers- so no recursive solutions please :) Thanks!