计数匹配元素以阵列 [英] Counting matching elements in an array
本文介绍了计数匹配元素以阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
由于两个同等大小的数组,我怎么能找到忽略的位置相匹配的元素个数?结果
的例如:的
Given two arrays of equal size, how can I find the number of matching elements disregarding the position?
For example:
-
[0,0,5]
和[0,5,5]
将返回一个匹配的2
,因为有一个0
和一个5
共通的。 -
[1,0,0,3]
和[0,0,1,4]
将返回3
的一场比赛,因为有0
的两场比赛和1 之一匹配code>;
-
[1,2,2,3]
和[1,2,3,4]
将返回3
。 的匹配
[0,0,5]
and[0,5,5]
would return a match of2
since there is one0
and one5
in common;[1,0,0,3]
and[0,0,1,4]
would return a match of3
since there are two matches of0
and one match of1
;[1,2,2,3]
and[1,2,3,4]
would return a match of3
.
我尝试了一些想法,但他们都倾向于得到相当粗糙和曲折。我猜有一些不错的红宝石成语,或者是一个正则表达式,这将是一个优雅的答案,这个解决方案。
I tried a number of ideas, but they all tend to get rather gnarly and convoluted. I'm guessing there is some nice Ruby idiom, or perhaps a regex that would be an elegant answer to this solution.
推荐答案
您可以用的 计数
:
You can accomplish it with count
:
a.count{|e| index = b.index(e) and b.delete_at index }
或 注
:
a.inject(0){|count, e| count + ((index = b.index(e) and b.delete_at index) ? 1 : 0)}
or with select
and length
(or it's alias – size
):
a.select{|e| (index = b.index(e) and b.delete_at index)}.size
结果:
-
A,B = [0,0,5],[0,5,5]
的输出:的= GT; 2
; -
A,B = [1,2,2,3],[1,2,3,4]
的输出:的=> 3
; -
A,B = [1,0,0,3],[0,0,1,4]
的输出的=> 3
。
a, b = [0,0,5], [0,5,5]
output:=> 2
;a, b = [1,2,2,3], [1,2,3,4]
output:=> 3
;a, b = [1,0,0,3], [0,0,1,4]
output=> 3
.
这篇关于计数匹配元素以阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文