ruby on rails - Check if each element of an array is included in a set of values of another array -
i using ruby on rails 3.0.7 , check if each element of array included in set of values present in array.
that is, have these arrays:
array1 = [1,3] array2 = [1,2,3,4,5]
and check if values in array1
present in array2
. i should return true
if @ least 1 of array1
different values in array2
how can code in ruby "good" way?
p.s.: read solution, java's arrays.
the easiest thing set intersection , see that:
intersection = array1 & array2 if intersection.length == array1.length # in array1 in array2 end
that would, of course, fail if array1
had duplicates intersection automatically compress those. have uniq
take care of that:
intersection = array1 & array2 if intersection.length == array1.uniq.length # in array1 in array2 end
if you're expecting duplicates in arrays you'd better off working instances of set rather arrays:
require 'set' s1 = set.new(array1) s2 = set.new(array2) if((s1 & s2) == s1) # in array1 in array2 end
or use subset?
better match intentions:
if(s1.subset?(s2)) # in array1 in array2 end
using sets take care of duplicate issues less noise having use uniq
time. there would, of course, bit of overhead should optimize clarity before performance (make work make fast if slow).
Comments
Post a Comment