Haskell:两个整数列表之间的匹配数?
假设我有两个整数列表:
4 12 24 26 35 41
42 24 4 36 2 26
这两个列表之间有 3 个匹配项。
如何计算 Haskell 中任意两个列表之间的匹配数?
谢谢。
Say I have two lists of integers:
4 12 24 26 35 41
42 24 4 36 2 26
There are 3 matches between the two lists.
How do I count the number of matches between any two list in Haskell?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您不需要处理多个元素,最简单的方法是计算交集的长度
如果您还有一个
,则使用
实例:Set
作为中间结构会更有效Ord如果您需要处理重复,使用
Map
计算每个元素出现的次数将是一个不太困难的修改。If you don't need to take care of multiple elements, the easy way is to calculate the length of the intersection
Somewhat more efficient is using
Set
s as intermediate structures, if you also have anOrd
instance:If you need to take care of repetitions, using a
Map
counting the number of occurrences for each element would be a not too difficult modification.处理列表会非常痛苦,因为你需要遍历所有的列表。像这样的东西通过形成所有相等的对然后计算大小来打印出正确的答案。
从性能的角度来看,这样做是相当尴尬的。对于大型列表,您最好使用集合,因为您可以比使用列表 (O(N)) 更快地测试成员资格(通常为 O(lg N),有时为 O(1) )。
It's going to be quite painful with lists as you've going to need to go through them all the pairs. Something like this prints out the right answer by forming all pairs where they are equal and then counting the size.
It's quite awkward to do it this way from a performance point of view. For large lists you're better off using a set as you can test membership quicker (typically O(lg N), sometimes O(1) ) than you can with a list (O(N)).
Data.List
中的函数intersect
返回两个给定列表之间的交集。The function
intersect
fromData.List
returns the intersection between two given lists.如果您想要一个仅使用列表的解决方案,并且不像 Data.List.intersect 那么慢,您可以使用以下命令:
If you want a solution using only lists, which is not so slow as
Data.List.intersect
, you can use this: