【问题标题】:Combining cells in a "simple combination" fashion以“简单组合”方式组合单元格
【发布时间】:2018-01-09 14:53:05
【问题描述】:

我在几个论坛和网站上寻找了一种方法来做到这一点,但没有找到任何线索...... 希望可以有人帮帮我!

这是我拥有的数据示例:

我想要这些单元格的排列,输出对,以反映特定学生在这些组中互动的次数。 换句话说,它是一个简单的组合。对于每个组,

  • 有 n!/p!*(n-p)!互动的可能性,
  • 其中“n”是每组的学生人数(在样本中,范围从 2 到 4)
  • 并且“p”等于 2(交互对)。

请注意,每个学生数组都有不同数量的学生。

因此,输出将是这样的:

这是我的第一篇文章,但我希望我说得足够清楚。

【问题讨论】:

标签: vba excel combinatorics


【解决方案1】:

免责声明:当您尝试解决问题时,阅读rules in StackOverflow 关于提出问题并提供一些代码确实是一个好主意。 StackOverflow 不是免费的编码服务等等。

不过,至少你截取了屏幕截图,这是一些东西。在某种方式。 下一步尝试将 Excel 单元格的值传递给数组或列表(无论您想要什么)。就我而言,我将它们硬编码为group1group4。这些组的数字一致,而不是名称一致,因为这种方式更快一些,更容易理解。在您的示例中,您可以考虑在最后重新映射它们:

Public Sub TestMe()

    Dim group1, group4
    Dim groupOfAll, group
    Dim student
    Dim cnt         As Long
    Dim cnt2        As Long

    group1 = Array(1, 2, 3)
    group4 = Array(4, 5, 6, 7)
    groupOfAll = Array(group1, group4)

    For Each group In groupOfAll
        cnt2 = 1
        For Each student In group
            For cnt = LBound(group) + cnt2 To UBound(group)
                Debug.Print student; "<>"; group(cnt)
            Next cnt
            cnt2 = cnt2 + 1
        Next student
        Debug.Print "----party------"
    Next group

End Sub

代码中棘手的部分是循环每个组的每个人,但在完成第一个人后,您不会再次循环遍历他。这是通过For cnt = LBound(group) + cnt2 To UBound(group)cnt2=cnt2+1 实现的。 cnt2 = 1,因为我们从 Array 中位置 0 的第一个元素开始,我们将这个学生“介绍”给下一个学生。结果如下:

 1 <> 2 
 1 <> 3 
 2 <> 3 
----party------
 4 <> 5 
 4 <> 6 
 4 <> 7 
 5 <> 6 
 5 <> 7 
 6 <> 7 
----party------

【讨论】:

    【解决方案2】:

    不幸的是,我没有设法在 VBA 中编写此代码。相反,我是用 Python 做的。这是代码,以防有人也需要:

    from itertools import combinations
    
    groups = open("C:\file.csv", "r")
    students = groups.readlines()
    for line in students:
        students2 = line.split(",")
        students3 = list(combinations(students2, 2))
        for edges in students3:
            edges2 = str(edges)
            print(edges2)
    
    groups.close()
    

    还是谢谢大家。

    【讨论】:

      猜你喜欢
      • 2020-05-28
      • 2014-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-05
      • 1970-01-01
      • 2012-05-23
      相关资源
      最近更新 更多