包含的集合数量的简明解决方案
假设我有一个简短的字符串列表,其中可以包含重复项:<“A”,“A”,“B”,“B”,“C”,“C”,“D”,“E”,“ F”>
然后假设我有一些其他字符串列表,它们可能是也可能不是原始列表的子集。我需要知道:
- 第二组是否“覆盖”第一组(例如,第一组中的每个项目是否也包含在第二组中)?
- 如果 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 但问题是它只返回不同的元素,因此在比较包含重复项的字符串列表时毫无用处。
大家有什么独特的想法吗?
Let's say I have a short list of strings, that can contain duplicates: <"A", "A", "B", "B", "C", "C", "D", "E", "F">
Then let's say I have some other string lists, which may or may not be subsets of the original list. I need to know:
- Does the second set "cover" the first set (e.g., is every item in the first set also contained in the second)?
- If 1 is true, how many instances of the second set does it take to recreate the first set?
So, in this case, if my second set was the list: <"A", "B", "C", "D", "E", "F">, I would get TRUE and 2.
If it was the list: <"A", "B", "C">, I would get FALSE.
If my first was <"A", "A", "A", "A", "B", "B", "B", "C", "C">:
- Second is <"A", "B", "C">: returns TRUE and 4.
- Second is <"A", "A", "B", "C">: returns TRUE and 3.
I know that this can be easily accomplished in N x M time using a nested loop. But I am looking for a (preferably Linq-based) solution that is concise and/or optimized. I played with Linq.Except but the problem with that is that it returns only the distinct elements, and is thereby useless when comparing lists of strings that contain duplicates.
Anyone have any unique ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
警告:如果
original
和secondList
都为空,则doesCover
将为true,但的计算instancesRequired
将抛出异常。因此,可能需要专门检查空列表。Caveat: If both
original
andsecondList
are empty, thendoesCover
will be true but the calculation ofinstancesRequired
will throw an exception. Might want to specifically check for empty lists therefore.