计数匹配元素以阵列 [英] Counting matching elements in an array

查看:62
本文介绍了计数匹配元素以阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于两个同等大小的数组,我怎么能找到忽略的位置相匹配的元素个数?结果
例如:

Given two arrays of equal size, how can I find the number of matching elements disregarding the position?
For example:


  1. [0,0,5] [0,5,5] 将返回一个匹配的 2 ,因为有一个 0 和一个 5 共通的。

  2. [1,0,0,3] [0,0,1,4] 将返回 3 的一场比赛,因为有 0 的两场比赛和 1 ;

  3. [1,2,2,3] [1,2,3,4] 将返回 3
  4. 的匹配
  1. [0,0,5] and [0,5,5] would return a match of 2 since there is one 0 and one 5 in common;
  2. [1,0,0,3] and [0,0,1,4] would return a match of 3 since there are two matches of 0 and one match of 1;
  3. [1,2,2,3] and [1,2,3,4] would return a match of 3.

我尝试了一些想法,但他们都倾向于得到相当粗糙和曲折。我猜有一些不错的红宝石成语,或者是一个正则表达式,这将是一个优雅的答案,这个解决方案。

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 aliassize):

a.select{|e| (index = b.index(e) and b.delete_at index)}.size

演示

结果:


  1. A,B = [0,0,5],[0,5,5] 输出: = GT; 2 ;

  2. A,B = [1,2,2,3],[1,2,3,4] 输出: => 3 ;

  3. A,B = [1,0,0,3],[0,0,1,4] 输出 => 3

  1. a, b = [0,0,5], [0,5,5] output: => 2;
  2. a, b = [1,2,2,3], [1,2,3,4] output: => 3;
  3. a, b = [1,0,0,3], [0,0,1,4] output => 3.

这篇关于计数匹配元素以阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆