What's the quickest way to find all possible pairs in list?

前端 未结 4 795
走了就别回头了
走了就别回头了 2021-01-14 05:03

Basically I have list of players, and I want to pair them up so that each player will play everyone once. What\'s the quickest way to find this data?

4条回答
  •  一向
    一向 (楼主)
    2021-01-14 06:00

    A simple divide and conquer algorithm:

    1. If there are only two people: Pair them and return them.
    2. Otherwise:

      1. Split the group in two groups of equal size.
      2. Find all pairings in each group using this algorithm recursively.
      3. Join the two lists.

        E.g. [[(a,b)]] and [[(c,d)]] becomes [[(a,b),(c,d)]].

      4. Find pairs across of the two groups, by rotating group two.

        E.g. [[(a,c),(b,d)],[(a,d),(b,c)]]

      5. Return (3) + (4)

    This algorithm runs in O(n^2) time, which is optimal, as it generates (n-1) rounds of n/2 pairings.

    For eight players you would get 7 rounds:

    [(a,b), (c,d), (e,f), (g,h)]
    [(a,c), (b,d), (e,g), (f,h)]
    [(a,d), (b,c), (e,h), (f,g)]
    [(a,e), (b,f), (c,g), (e,h)]
    [(a,f), (b,g), (c,h), (e,e)]
    [(a,g), (b,h), (c,e), (e,f)]
    [(a,h), (b,e), (c,f), (e,g)]
    

提交回复
热议问题