1

Newb programmer here, I'm most familiar with Python but also learning C and Java, so either of 3 would be fine.
What I have is a string of letters, say:

ABXDEYGH

However say,

X is possible to be M and N.
Y is possible to be P and Q.

In this example, I would like basically to print all possible variations of this string of letters.
Like:

ABMDEPGH
ABNDEPGH
ABMDEQGH
ABNDEQGH

Any help would be appreciated. Thanks in advance

AakashM
  • 62,551
  • 17
  • 151
  • 186
user839145
  • 6,883
  • 3
  • 16
  • 10
  • possible duplicate of [Calculate all combinations of a series](http://stackoverflow.com/questions/759259/calculate-all-combinations-of-a-series) – Mike Samuel Nov 01 '11 at 21:50

2 Answers2

2

This boils down to a simple problem of permutations. What you care about is the part of the text that can change; the variables. The rest can be ignored, until you want to display it.

So your question can be more simply stated: What are all the possible permutations of 1 item from set X and another item from set Y? This is known as a cross-product, sometimes also simply called a product.

Here's a possible Python solution:

import itertools

x = set(['M', 'N'])
y = set(['P', 'Q'])

for items in itertools.product(x, y)
    print 'AB{0}DE{1}GH'.format(*items)

Note that the print ''.format() command uses the "unpack arguments" notation described here.

Community
  • 1
  • 1
Lemur
  • 442
  • 6
  • 11
1

why dont you write two loops. one to replace all possible characters with X and one for Y.

foreach(char c in charSet1){
   // replaces X
   foreach(char ch in charSet2){
     // replace Y 
   }

}
DarthVader
  • 52,984
  • 76
  • 209
  • 300