Reputation: 111
Although there are numerous articles about generating permutations, I have an algorithmic need for permutation that's just a bit different.
Given a set of elements (a, b, c, .. n) I construct pairs: (ab), (cd), (ef), ... in any combination of elements. Pairs (ab) and (ba) are identical. Also the needed permutations should not be different only in sequence: (ab), (ef), (cd) is identical to (ef), (cd), (ab)
As an example, I'll show the exhaustive list of permutations for 6 elements a, b, c, d, e, f.
This is the list of pairs I would like the algorithm to generate:
(ab), (cd), (ef)
(ab), (ce), (df)
(ab), (cf), (de)
(ac), (bd), (ef)
(ac), (be), (df)
(ac), (bf), (de)
(ad), (bc), (ef)
(ad), (be), (cf)
(ad), (bf), (ce)
(ae), (bc), (df)
(ae), (bd), (cf)
(ae), (bf), (cd)
(af), (bc), (de)
(af), (bd), (ce)
(af), (be), (cd)
I tried to envision the algorithm for 4 pairs (8 elements), but I couldn't.
Typical for the solution is, that all lines start with element a. Any other starting element could give a conflict with the two rules that (ab) equals (ba) and (cd), (ab) equals (ab), (cd). So starting all with element a is the easiest way to avoid duplicates.
I tried to find the answer with Knuth, but I'm too little of a mathematician to be able to find this particular exercise in the 100 or so given in the chapter on permutations and combinations. It's probably there, but not for me to find.
Hope someone here can show me a good algorithm (preferably in Pascal or in C).
Upvotes: 2
Views: 3321
Reputation: 542
As your each pair has sub pair of 2 elements so I am assuming length of you character list is even.
Algorithm
Python Code
Here I am providing code implementing above algorithm in python:
# Keep coding and change the world..And do not forget anything..Not Again..
def func(chr_list, pair=""):
l = len(chr_list)
if l == 2:
print pair + '(' + chr_list[0] + chr_list[1] + ')'
else:
i = 0
l -= 1
ch1 = chr_list[0]
chr_list = chr_list[1:]
while i < l:
ch2 = chr_list[i]
chr_list.remove(ch2)
func(chr_list[:], pair + '(' + ch1 + ch2 + '), ')
chr_list.insert(i, ch2)
i += 1
func(['a', 'b', 'c', 'd', 'e', 'f'])
Hope this will help you.
Upvotes: 2