3

Given a list L of an even number (2k) of elements, I'm looking for an algorithm to produce a list of 2k-1 sublists with the following properties:

  1. each sublist includes exactly k 2-combinations (pairs where the order does not matter) of elements from L,
  2. each sublist includes every elements from L exactly once, and
  3. the union of all elements from all sublists is exactly the set of all possible 2-combinations of the elements from L.

For example, if the input list is L = [a, b, c, d], we have k = 2 with 3 sublists, each including 2 pairs. A possible solution would look like [[ab, cd], [ac, bd], [ad, bc]]. If we ignore the ordering for all elements in the lists (think of all lists as sets), it turns out that this is also the only solution for k = 2.

My aim now is not only to find a single solution but all possible solutions. As the number of involved combinations grows pretty quickly, it would be nice to have all results be constructed in a clever way instead of generating a huge list of candidates and removing the elements from it that don't satisfy the given properties. Such a naïve algorithm could look like the following:

  1. Find the set C of all 2-combinations for L.
  2. Find the set D of all k-combinations for C.
  3. Choose all sets from D that union equals L, call the new set D'.
  4. Find the set E of all (2k-1)-combinations for D'.
  5. Choose all sets from E that union is the set C, and let the new set be the final output.

This algorithm is easy to implement but it's incredibly slow for bigger input lists. So is there a way to construct the result list more efficently?


Edit: Here is the result for L = [a,b,c,d,e,f] with k = 3, calculated by the above algorithm:

[[[ab,cd,ef],[ac,be,df],[ad,bf,ce],[ae,bd,cf],[af,bc,de]],
 [[ab,cd,ef],[ac,bf,de],[ad,be,cf],[ae,bc,df],[af,bd,ce]],
 [[ab,ce,df],[ac,bd,ef],[ad,be,cf],[ae,bf,cd],[af,bc,de]],
 [[ab,ce,df],[ac,bf,de],[ad,bc,ef],[ae,bd,cf],[af,be,cd]],
 [[ab,cf,de],[ac,bd,ef],[ad,bf,ce],[ae,bc,df],[af,be,cd]],
 [[ab,cf,de],[ac,be,df],[ad,bc,ef],[ae,bf,cd],[af,bd,ce]]]

All properties are satisfied:

  1. each sublist has k = 3 2-combinations,
  2. each sublist only includes each element once, and
  3. the union of all 2k-1 = 5 sublists for one solution is exactly the set of all possible 2-combinations for L.

Edit 2: Based on user58697's answer, I improved the calculation algorithm by using the round-robin tournament scheduling:

  1. Let S be the result set, starting with an empty set, and P be the set of all permutations of L.
  2. Repeat the following until P is empty:
    • Select an arbitrary permutation from P
    • Perform full RRT scheduling for this permutation. In each round, the arrangement of elements from L forms a permutation of L. Remove all these 2k permutations from P.
    • Add the resulting schedule to S.
  3. Remove all lists from S if the union of their sublists has duplicate elements (i.e. doesn't add up to all 2-combinations of L).

This algorithm is much more performant than the first one. I was able to calculate the number of results for k = 4 as 960 and k = 5 as 67200. The fact that there doesn't seem to be an OEIS result for this sequence makes me wonder if the numbers are actually correct, though, i.e. if the algorithm is producing the complete solution set.

Guy Coder
  • 22,011
  • 6
  • 54
  • 113
siracusa
  • 2,550
  • 1
  • 7
  • 19
  • Your list L has 2k elements, and each "sublist" is a partition of L into k parts of size 2 each. There are exactly (2k)!/(2^k k!) such partitions (for your case of k=2, that is 3). Now, for k=2 it turns out that the number of partitions, 3, also happens to be 2k-1. But in general it will be much larger. For example, for k=3 there are 15 partitions of {a, b, c, d, e, f} into 3 parts of size 2 each. Do you want all 5-subsets of these 15 partitions? Or do you just want these 15 partitions? – ShreevatsaR Feb 08 '17 at 18:38
  • Going just one step further: for k=4, there are [105](https://oeis.org/A0011470) ways to partition a list like {a, b, c, d, e, f, g, h} into four (unordered) pairs. I _think_ what you want is just the list of 105 partitions, and the mention of (2k-1) in your question is a mistake. Otherwise, with 2k-1=7 if you really want all size-7 subsets from these 105 partitions, the number of them is [22760723700 ≈ 2.2×10^{10}](https://www.wolframalpha.com/input/?i=(105+choose+7)). What are you going to do with each of them? And forget about [k=5](https://www.wolframalpha.com/input/?i=(945+choose+9)). – ShreevatsaR Feb 08 '17 at 19:02
  • The 2k-1 is correct, I think. Note that I'm not looking for the huge number of combinations you mentioned, but that these would just be temporary candidates in the algorithm I presented. The final step removes many of these combinations because their union doesn't add up to all the 2-combinations of the input list. For example, if k=3, the number of result lists/sets is 6, not 15. – siracusa Feb 08 '17 at 19:56
  • With k=3, these are the 15 partitions of {a, b, c, d, e, f} into unordered pairs: 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. How do you get 6? And 2k-1=5, so how do you get 5? – ShreevatsaR Feb 08 '17 at 20:32
  • @ShreevatsaR You seem to be missing the final steps of the algorithm, where we arrange the partitions in such a way that we get all possible 2-combinations in one solution. I added the results for k=3, but I really don't know how to make the problem description anymore clear. – siracusa Feb 09 '17 at 04:48
  • Ah great, with the k=3 example it's much more clear; I understand now! And it's also clear why there are 2k-1 in each "row": there are totally (2k choose 2) = k(2k-1) pairs, and as each partition has k pairs, there will be exactly (2k-1) in each row. The number of rows (1 for k=2 and 6 for k=3) is interesting and probably also fast-growing (probably growing even faster than the number of partitions); it's an interesting problem and I will continue think about it. Sorry it took a while to understand! – ShreevatsaR Feb 09 '17 at 05:17
  • No worries, thanks for your time! – siracusa Feb 09 '17 at 07:24
  • I just came here to post. I think there's a bug in your counts. I wrote a program just now, and was able to get count 6240 for k=4, which (along with the counts 1 for k=2 and 6 for k=3) leads to [A000438 on OEIS](https://oeis.org/A000438). I can generate all 6240 results for k=4 in a couple of seconds, but there are 1225566720 results for k=5 which seems to be not very useful to generate (even if we can optimize it to run in a few hours). – ShreevatsaR Feb 09 '17 at 14:38
  • BTW after reading the definition of [graph factorization](https://en.wikipedia.org/wiki/Graph_factorization), it is clear that your problem is exactly to enumerate all the 1-factorizations of the complete graph on 2k vertices, which is what OEIS A000438 counts. So theory matches practice. Let me know if you'd like me to post my program for k ≤ 4 (won't bother with k=5). Also curious what your original motivation was :-) – ShreevatsaR Feb 09 '17 at 14:43
  • My actual problem is even more complicated, as the input elements can have additional attributes. I wanted to calculate all solutions to run different attribute metrics on these and find an optional match (e.g. avoid to pair a blue item with a red one in round x if it was paired with a red one in round x-1). As the number of results seems to grow quicker than expected, this is impractical. However, the RRT scheduling algorithm is a good heuristical approach that yields satisfying results for me. Post your code anyway, I'm curious. And thanks again, learned new things in this conversion. :) – siracusa Feb 10 '17 at 06:26
  • I've posted my code in an answer; let me know if you've taken a look at it. I realized while typing the answer that the solution for k=5 can be optimized by generating only a few and using symmetries, but oh well. By the way, the number of solutions (the number of 1-factorizations) is precisely the number of ways to organize a round-robin tournament. – ShreevatsaR Feb 13 '17 at 22:01

2 Answers2

2

It is a round-robin tournament scheduling:

  1. A pair is a match,
  2. A list is a round (each team plays with some other team)
  3. A set of list is an entire tournament (each team plays each other team exactly once).

Take a look here.

user58697
  • 6,907
  • 1
  • 11
  • 24
  • 1
    That looks like an alternative algorithm for calculating one such scheduling. How do you get all possible schedulings (or at least a bigger number of results you can choose the best from according to different metrics)? – siracusa Feb 08 '17 at 19:59
1

This was an interesting question. In the process of answering it (basically after writing the program included below, and looking up the sequence on OEIS), I learned that the problem has a name and rich theory: what you want is to generate all 1-factorizations of the complete graph K2k.


Let's first restate the problem in that language:

You are given a number k, and a list (set) L of size 2k. We can view L as the vertex set of a complete graph K2k.

  • For example, with k=3, L could be {a, b, c, d, e, f}

A 1-factor (aka perfect matching) is a partition of L into unordered pairs (sets of size 2). That is, it is a set of k pairs, whose disjoint union is L.

  • For example, ab-cd-ef is a 1-factor of L = {a, b, c, d, e, f}. This means that a is matched with b, c is matched with d, and e is matched with f. This way, L has been partitioned into three sets {a, b}, {c, d}, and {e, f}, whose union is L.

Let S (called C in the question) denote the set of all pairs of elements of L. (In terms of the complete graph, if L is its vertex set, S is its edge set.) Note that S contains (2k choose 2) = k(2k-1) pairs. So for k = 0, 1, 2, 3, 4, 5, 6…, S has size 0, 1, 6, 15, 28, 45, 66….

  • For example, S = {ab, ac, ad, ae, af, bc, bd, be, bf, cd, ce, cf, de, df, ef} for our L above (k = 3, so |S| = k(2k-1) = 15).

A 1-factorization is a partition of S into sets, each of which is itself a 1-factor (perfect matching). Note that as each of these matchings has k pairs, and S has size k(2k-1), the partition has size 2k-1 (i.e., is made of 2k-1 matchings).

  • For example, this is a 1-factorization: {ab-cd-ef, ac-be-df, ad-bf-ce, ae-bd-cf, af-bc-de}

In other words, every element of S (every pair) occurs in exactly one element of the 1-factorization, and every element of L occurs exactly once in each element of the 1-factorization.

The problem asks to generate all 1-factorizations.


Let M denote the set of all 1-factors (all perfect matchings) of L. It is easy to prove that M contains (2k)!/(k!2^k) = 1×3×5×…×(2k-1) matchings. For k = 0, 1, 2, 3, 4, 5, 6…, the size of M is 1, 1, 3, 15, 105, 945, 10395….

  • For example, for our L above, M = {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} (For k=3 this number 15 is the same as the number of pairs, but this is just a coincidence as you can from the other numbers: this number grows much faster than the number of pairs.)

M is easy to generate:

def perfect_matchings(l):
    if len(l) == 0:
        yield []
    for i in range(1, len(l)):
        first_pair = l[0] + l[i]
        for matching in perfect_matchings(l[1:i] + l[i+1:]):
            yield [first_pair] + matching

For example, calling perfect_matchings('abcdef') yields the 15 elements ['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'] as expected.

By definition, a 1-factorization is a partition of S into elements from M. Or equivalently, any (2k-1) disjoint elements of M form a 1-factorization. This lends itself to a straightforward backtracking algorithm:

  • start with an empty list (partial factorization)
  • for each matching from the list of perfect matchings, try adding it to the current partial factorization, i.e. check whether it's disjoint (it should not contain any pair already used)
    • if fine, add it to the partial factorization, and try extending

In code:

matching_list = []
pair_used = defaultdict(lambda: False)
known_matchings = []  # Populate this list using perfect_matchings()
def extend_matching_list(r, need):
    """Finds ways of extending the matching list by `need`, using matchings r onwards."""
    if need == 0:
        use_result(matching_list)
        return
    for i in range(r, len(known_matchings)):
        matching = known_matchings[i]
        conflict = any(pair_used[pair] for pair in matching)
        if conflict:
            continue  # Can't use this matching. Some of its pairs have already appeared.
        # Else, use this matching in the current matching list.
        for pair in matching:
            pair_used[pair] = True
        matching_list.append(matching)
        extend_matching_list(i + 1, need - 1)
        matching_list.pop()
        for pair in matching:
            pair_used[pair] = False

If you call it with extend_matching_list(0, len(l) - 1) (after populating known_matchings), it generates all 1-factorizations. I've put the full program that does this here. With k=4 (specifically, the list 'abcdefgh'), it outputs 6240 1-factorizations; the full output is here.


It was at this point that I fed the sequence 1, 6, 6240 into OEIS, and discovered OEIS A000438, sequence 1, 1, 6, 6240, 1225566720, 252282619805368320,…. It shows that for k=6, the number of solutions ≈2.5×1017 means that we can give up hope of generating all solutions. Even for k=5, the ≈1 billion solutions (recall that we're trying to find 2k-1=9 disjoint sets out of the |M|=945 matchings) will require some carefully optimized programs.

The first optimization (which, embarrassingly, I only realized later by looking closely at trace output for k=4) is that (under natural lexicographic numbering) the index of the first matching chosen in the partition cannot be greater than the number of matchings for k-1. This is because the lexicographically first element of S (like "ab") occurs only in those matchings, and if we start later than this one we'll never find it again in any other matching.

The second optimization comes from the fact that the bottleneck of a backtracking program is usually the testing for whether a current candidate is admissible. We need to test disjointness efficiently: whether a given matching (in our partial factorization) is disjoint with the union of all previous matchings. (Whether any of its k pairs is one of the pairs already covered by earlier matchings.) For k=5, it turns out that the size of S, which is (2k choose 2) = 45, is less than 64, so we can compactly represent a matching (which is after all a subset of S) in a 64-bit integer type: if we number the pairs as 0 to 44, then any matching can be represented by an integer having 1s in the positions corresponding to elements it contains. Then testing for disjointness is a simple bitwise operation on integers: we just check whether the bitwise-AND of the current candidate matching and the cumulative union (bitwise-OR) of previous matchings in our partial factorization is zero.

A C++ program that does this is here, and just the backtracking part (specialized for k=5) does not need any C++ features so it's extracted out as a C program here. It runs in about 4–5 hours on my laptop, and finds all 1225566720 1-factorizations.

Another way to look at this problem is to say that two elements of M have an edge between them if they intersect (have a pair (element of S) in common), and that we're looking for all maximum independent set in M. Again, the simplest way to solve that problem would still probably be backtracking (we'd write the same program).

Our programs can be made quite a lot more efficient by exploiting the symmetry in our problem: for example we could pick any matching as our first 1-factor in the 1-factorization (and then generate the rest by relabelling, being careful not to avoid duplicates). This is how the number of 1-factorizations for K12 (the current record) was calculated.


A note on the wisdom of generating all solutions

In The Art of Computer Programming Volume 4A, at the end of section 7.2.1.2 Generating All Permutations, Knuth has this important piece of advice:

Think twice before you permute. We have seen several attractive algorithms for permutation generation in this section, but many algorithms are known by which permutations that are optimum for particular purposes can be found without running through all possibilities. For example, […] the best way to arrange records on a sequential storage […] takes only O(n log n) steps. […] the assignment problem, which asks how to permute the columns of a square matrix so that the sum of the diagonal elements is maximized […] can be solved in at most O(n3) operations, so it would be foolish to use a method of order n! unless n is extremely small. Even in cases like the traveling salesrep problem, when no efficient algorithm is known, we can usually find a much better approach than to examine every possible solution. Permutation generation is best used when there is good reason to look at each permutation individually.

This is what seems to have happened here (from the comments below the question):

I wanted to calculate all solutions to run different attribute metrics on these and find an optional match […]. As the number of results seems to grow quicker than expected, this is impractical.

Generally, if you're trying to "generate all solutions" and you don't have a very good reason for looking at each one (and one almost never does), there are many other approaches that are preferable, ranging from directly trying to solve an optimization problem, to generating random solutions and looking at them, or generating solutions from some subset (which is what you seem to have done).


Further reading

Following up references from OEIS led to a rich history and theory.

  • On 1-factorizations of the complete graph and the relationship to round robin schedules, Gelling (M. A. Thesis), 1973

  • On the number of 1-factorizations of the complete graph, Charles C Lindner, Eric Mendelsohn, Alexander Rosa (1974?) -- this shows that the number of nonisomorphic 1-factorizations on K2n goes to infinity as n goes to infinity.

  • E. Mendelsohn and A. Rosa. On some properties of 1-factorizations of complete graphs. Congr. Numer, 24 (1979): 739–752

  • E. Mendelsohn and A. Rosa. One factorizations of the complete graph: A survey. Journal of Graph Theory, 9 (1985): 43–65 (As long ago as 1985, this exact question was studied well-enough to need a survey!)

  • Via papers of Dinitiz:

  • Various One-Factorizations of Complete Graphs by Gopal, Kothapalli, Venkaiah, Subramanian (2007). A paper that is relevant to this question, and has many useful references.

  • W. D. Wallis, Introduction to Combinatorial Designs, Second Edition (2007). Chapter 10 is "One-Factorizations", Chapter 11 is "Applications of One-Factorizations". Both are very relevant and have many useful references.

  • Charles J. Colbourn and Jeffrey H. Dinitz, Handbook of Combinatorial Designs, Second Edition (2007). A goldmine. See chapters VI.3 Balanced Tournament Designs, VI.51 Scheduling a Tournament, VII.5 Factorizations of Graphs (including its sections 5.4 Enumeration and Tables, 5.5 Some 1-Factorizations of Complete Graphs), VII.6 Computational Methods in Design Theory (6.2 Exhaustive Search). This last chapter references:

    • [715] How K12 was calculated ("orderly algorithm"), a backtracking -- the Dinitz-Garnick-McKay paper mentioned above
    • [725] “Contains, among many other subjects related to factorization, a fast algorithm for finding 1-factorizations of K2n.” ("Room squares and related designs", J. H. Dinitz and S. R. Stinson)
    • [1270] (P. Kaski and P. R. J. Östergård, One-factorizations of regular graphs of order 12, Electron. J. Comb. 12, Research Paper 2, 25 pp. (2005))
    • [1271] “Contains the 1-factorizations of complete graphs up to order 10 in electronic form.” (P. Kaski and P. R. J. Östergård, Classification Algorithms for Codes and Designs, Springer, Berlin, 2006.)
    • [1860] “A survey on perfect 1-factorizations of K2n” (E. S. Seah, Perfect one-factorizations of the complete graph—A survey, Bull. Inst. Combin. Appl. 1 (1991) 59–70)
    • [2107] “A survey of 1-factorizations of complete graphs including most of the material of this chapter.” W. D. Wallis, One-factorizations of complete graphs, in Dinitz and Stinson (ed), Contemporary Design Theory, 1992
    • [2108] “A book on 1-factorizations of graphs.” W. D. Wallis, "One-Factorizations", Kluwer, Dordrecht, 1997

Some other stuff:

ShreevatsaR
  • 35,974
  • 16
  • 97
  • 122
  • A Google search for 98758655816833727741338583040 (the largest computed value in the sequence so far) gives some relevant results, e.g. [the paper that computed it](https://arxiv.org/abs/0801.0202). – ShreevatsaR Feb 13 '17 at 21:22