【问题标题】:maximizing number of sets that form an intersection最大化形成交集的集合数
【发布时间】:2019-03-11 09:13:26
【问题描述】:

假设我有 10 个集合,每个集合都有一些随机数量的正整数。

现在,我想最大化可以形成交集的集合的数量(不搜索最大的交集),假设一个集合只能与另一个集合形成交集,如果至少“x”个整数重叠。例如,如果x = 2,则[1,2,3,4] 不能与[1,5,6,7] 形成交集,因为重叠的整数只有 1 个,而不是 2 个。

要注意的另一件事(虽然很明显)是,对于x=2,如果我有[1,2,3,4][1,2,6,7],则可能会发生交集,并且对于第三组形成交集,它必须在某处有[1,2]在集合中。

我无法正确地形成一个算法来做到这一点,因为可以通过指数方式来比较这些集合!即使我只有 3 个集合,考虑到集合的大小,我也必须考虑给定交集约束的每个子集组合比较。

我正在按如下方式生成我的集合:

sets = []
for i in range(0,10):
    temp = np.random.randint(1,3000)
    sets.append(set(np.random.randint(1, 3000, temp)))

【问题讨论】:

    标签: python algorithm set


    【解决方案1】:

    您可以计算每个数字在集合中出现的次数。由于您正在尝试最大化交叉点的总数,因此最常见的数字将导致可能的交叉点数量最多(理想情况下,每 2 个集合形成一个交叉点)。这是代码:

    import numpy as np
    
    # Set a seed for testing purposes
    np.random.seed(1)
    
    # Initialise the min number of elements in an intersection
    x = 2
    
    # Initialise the list of sets
    sets = list()
    
    # Initialise the count mapping
    count = dict()
    
    # Generate the sets
    for i in range(0,10):
        temp = np.random.randint(1,3000)
        sets.append(set(np.random.randint(1, 3000, temp)))
    
    # Count each number's occurrence
    for s in sets:
        for number in s:
            if number in count:
                count[number] +=1
            else:
                count[number] = 1
    
    # Sort the result (by the count number)
    l = sorted(count, key=lambda x: count[x], reverse=True)
    
    # Print the number of occurrences (within the boundary of min x elements)
    print(count[l[x-1]])
    
    # Print the numbers that give you the maximum number of intersections
    print(l[:x])
    

    结果是:

    7
    [2270, 2225]
    

    在这种情况下,10 个集合中有 7 个包含数字 2270 和 2225,因此可以形成总共 21 (6*7/2) 个交叉点。性能应该是O(NlogN)(由于排序),其中 N 是数字的总数。

    【讨论】:

      【解决方案2】:

      考虑 A 的所有子集。(总共 2^10 个子集)

      ss 是 A 的子集,

      检查ss的交集SI,如果len(SI) > x,则更新结果。

      伪代码:

      result = set()
      
      for ss in   all subset:
          SI = ss[0]
          for g in ss:
              SI = SI .intersection(g)
          if len(SI ) >= x:
              result = ss 
      print(result)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-06
        • 1970-01-01
        相关资源
        最近更新 更多