You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python组合优化:6人高尔夫配对矩阵构建与优化问询

6人高尔夫5轮分组配对:构建完整配对次数统计矩阵

问题背景

计划组织6人(选手[a,b,c,d,e,f])高尔夫旅行,需优化5轮3人分组配对。已通过Python的itertools生成所有3人组合并补全每组剩余选手,随机抽取5轮分组后,目标是构建选手间的配对次数交叉矩阵,以此找到重复配对最少的分组组合。目前仅能统计选手a与其他选手的配对次数,无法生成完整矩阵,需实现完整统计方法。

现有实现代码

生成所有分组组合

import pandas as pd
from itertools import permutations, combinations

players = ['a','b','c','d','e','f']
# 生成所有3人组合
z = pd.DataFrame(combinations(players,3))
# 补全每组的剩余3名选手
for i in z.index:
    remaining_players = players.copy()
    remaining_players.remove(z.loc[i,0])
    remaining_players.remove(z.loc[i,1])
    remaining_players.remove(z.loc[i,2])
    z.loc[i,3] = remaining_players[0]
    z.loc[i,4] = remaining_players[1]
    z.loc[i,5] = remaining_players[2]

生成的z矩阵(所有可能的分组):

0  1  2  3  4  5
0  a  b  c  d  e  f
1  a  b  d  c  e  f
2  a  b  e  c  d  f
3  a  b  f  c  d  e
4  a  c  d  b  e  f
5  a  c  e  b  d  f
6  a  c  f  b  d  e
7  a  d  e  b  c  f
8  a  d  f  b  c  e
9  a  e  f  b  c  d

现有统计代码(仅统计选手a的配对次数)

# 随机抽取5轮分组
v = z.sample(5)
# 初始化空矩阵
opt = pd.DataFrame([], index=players, columns=players)
# 统计选手a的配对次数
g = pd.concat([v[1].value_counts(),v[2].value_counts()]).sort_index().groupby(level=0).sum()

输出的选手a配对次数统计:

b    3
c    1
d    1
e    3
f    2

期望结果

得到完整的配对次数交叉矩阵(示例):

a    b    c    d    e    f
a  0  0.0  0.0  0.0  0.0  0.0
b  3  0.0  0.0  0.0  0.0  0.0
c  1  1    0.0  0.0  0.0  0.0
d  1  3    3    0.0  0.0  0.0
e  3  1    3    1    0.0  0.0
f  2  1    2    2    2    0.0 

对应抽样分组示例:

0  1  2  3  4  5
3  a  b  f  c  d  e
2  a  b  e  c  d  f
5  a  c  e  b  d  f
1  a  b  d  c  e  f
9  a  e  f  b  c  d

完整矩阵统计实现方法

代码实现

import pandas as pd
from itertools import combinations

players = ['a','b','c','d','e','f']

# 初始化全0配对矩阵,对角线为0(自己与自己无配对)
pair_matrix = pd.DataFrame(0, index=players, columns=players)

# 遍历每一轮分组
for _, row in v.iterrows():
    # 拆分当前轮的两个3人组
    group1 = row[0:3].tolist()
    group2 = row[3:6].tolist()
    
    # 处理每个组内的所有两两配对
    for group in [group1, group2]:
        # 生成组内所有不重复的两两组合
        for p1, p2 in combinations(group, 2):
            # 双向计数(保证矩阵对称),若只需单向统计可仅保留一行
            pair_matrix.loc[p1, p2] += 1
            pair_matrix.loc[p2, p1] += 1

# 确保对角线为0(自己与自己无配对)
for p in players:
    pair_matrix.loc[p, p] = 0

print(pair_matrix)

代码说明

  1. 初始化矩阵:创建以选手为行和列的全0矩阵,确保初始状态下所有配对次数为0。
  2. 遍历分组:对每一轮的两个3人组分别处理,生成组内所有两两选手的组合。
  3. 计数配对:每出现一次两两配对,就将矩阵中对应位置的计数加1,双向计数保证矩阵对称。
  4. 对角线置0:强制选手与自己的配对次数为0,符合实际逻辑。

输出示例(对应给定抽样分组)

运行代码后会生成与期望结构一致的完整矩阵,准确统计所有选手间的配对次数。

优化方向(可选)

若要找到重复配对最少的分组组合,可基于上述统计逻辑,结合随机抽样+评分(比如计算所有配对次数的方差或最大值,数值越小说明分组越均匀)的方式,筛选出最优的5轮分组组合。


内容的提问来源于stack exchange,提问作者user2109046

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 02:23:13