问题
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).
回答1:
As your each pair has sub pair of 2 elements so I am assuming length of you character list is even.
Algorithm
- Take first element of you list and pair this with each of element remaining in the list.
- Then making each pair remove that two elements from your list and now your problem is reduced to a list having two elements less.
- Now repeat this procedure until your list size becomes 2.
- Now this one is the last sub pair of the required pair.
- You are done.
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.
来源:https://stackoverflow.com/questions/38532865/algorithm-to-generate-all-permutations-of-pairs-without-repetition