c# - 包含的集合数量的简明解决方案

标签 c# algorithm performance pattern-matching

假设我有一个简短的字符串列表,其中可以包含重复项:<"A"、"A"、"B"、"B"、"C"、"C"、"D"、"E", "F">

然后假设我有一些其他字符串列表,它们可能是也可能不是原始列表的子集。我需要知道:

  1. 第二组是否“覆盖”了第一组(例如,第一组中的每一项是否也包含在第二组中)?
  2. 如果 1 为真,则需要多少个第二组实例才能重新创建第一组?

因此,在这种情况下,如果我的第二组是列表:<"A"、"B"、"C"、"D"、"E"、"F">,我将得到 TRUE 和 2。

如果是列表:<"A", "B", "C">,我会得到 FALSE。

如果我的第一个是<"A", "A", "A", "A", "B", "B", "B", "C", "C">:

  • 第二个是 <"A", "B", "C">:返回 TRUE 和 4。
  • 第二个是 <"A", "A", "B", "C">:返回 TRUE 和 3。

我知道这可以使用嵌套循环在 N x M 时间内轻松完成。但我正在寻找一种(最好是基于 Linq 的)简洁和/或优化的解决方案。我玩过 Linq.Except 但问题是它只返回不同的元素,因此在比较包含重复项的字符串列表时毫无用处。

大家有什么独特的想法吗?

最佳答案

Does the second set "cover" the first set (e.g., is every item in the first set also contained in the second)?

// Assuming that the elements are comparable (strings are);
// if not, need to implement your own IComparer<T>
var doesCover = !original.Except(secondList).Any();

How many instances of the second set does it take to recreate the first set?

var instancesRequired = secondList.GroupBy(e => e)
    .Max(gr => (original.Count(e => e.Equals(gr.Key))
               + gr.Count() - 1) / gr.Count());

警告:如果 originalsecondList 都为空,则 doesCover 将为真,但计算instancesRequired 将抛出异常。因此可能需要专门检查空列表。

关于c# - 包含的集合数量的简明解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4686346/

相关文章:

c++ - 使用 Hoare 分区方案的快速排序算法返回原始未排序列表

Python:计算N个多元正态分布的值的可能性

performance - HBase - 快照性能

c# - 如何在 LINQ Where() 中使用额外的 int 参数

c# - WPF MVVM : EventTrigger is not working inside CheckBox

c# - 在 C# 中,改进单元测试反馈循环的好方法是什么?

c++ - 当您只能在运行时将基类向下转换为子类时,消除 C++ 虚函数

algorithm - 在有向图中找到可以到达所有其他顶点的顶点

mysql - 检查MySQL中是否存在数千条记录

java - ActiveMQ 5.15.9 安全