ruby - Counting matching elements in an array -


given 2 arrays of equal size, how can find number of matching elements disregarding position?
for example:

  1. [0,0,5] , [0,5,5] return match of 2 since there 1 0 , 1 5 in common;
  2. [1,0,0,3] , [0,0,1,4] return match of 3 since there 2 matches of 0 , 1 match of 1;
  3. [1,2,2,3] , [1,2,3,4] return match of 3.

i tried number of ideas, tend rather gnarly , convoluted. i'm guessing there nice ruby idiom, or perhaps regex elegant answer solution.

you can accomplish count:

a.count{|e| index = b.index(e) , b.delete_at index } 

demonstration

or inject:

a.inject(0){|count, e| count + ((index = b.index(e) , b.delete_at index) ? 1 : 0)} 

demonstration

or select , length (or it's aliassize):

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

demonstration

results:

  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.

Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -