ruby - Counting matching elements in an array -
given 2 arrays of equal size, how can find number of matching elements disregarding position?
for example:
[0,0,5],[0,5,5]return match of2since there 10, 15in common;[1,0,0,3],[0,0,1,4]return match of3since there 2 matches of0, 1 match of1;[1,2,2,3],[1,2,3,4]return match of3.
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 } or inject:
a.inject(0){|count, e| count + ((index = b.index(e) , b.delete_at index) ? 1 : 0)} or select , length (or it's alias – size):
a.select{|e| (index = b.index(e) , b.delete_at index)}.size results:
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.
Comments
Post a Comment