Find a set of common elements from a multi-dimensional array

S

Shreyas Satish

I have a multi-dimensional array ; a=[[2,3,4],[1,3,4],[1,2],[1,2,3,4]]
i've to compare all the 4 sub-arrays and get common elements.Next,take 3
subarrays at a time and get common elements.then take 2 sub arrays at a
time and get common elements.
 
J

Jean-Julien Fleck

Hello,

2010/4/6 Shreyas Satish said:
I have a multi-dimensional array ; a=3D[[2,3,4],[1,3,4],[1,2],[1,2,3,4]]
i've to compare all the 4 sub-arrays and get common elements.Next,take 3
subarrays at a time and get common elements.then take 2 sub arrays at a
time and get common elements.

Have a look to Array#combination to group your subarrays into
comparison sets and then use the Set class (require 'set') and it's
intersection instance method to get the common elements.

Cheers,

--=20
JJ Fleck
PCSI1 Lyc=E9e Kl=E9ber
 
A

Aldric Giacomoni

Shreyas said:
I have a multi-dimensional array ; a=[[2,3,4],[1,3,4],[1,2],[1,2,3,4]]
i've to compare all the 4 sub-arrays and get common elements.Next,take 3
subarrays at a time and get common elements.then take 2 sub arrays at a
time and get common elements.

Well, the way to get common elements between arrays is with the
"intersection" method:
http://ruby-doc.org/core/classes/Array.html#M002212 (of course,
available as a Set operation too:
http://ruby-doc.org/core/classes/Set.html#M001621)

And what you're looking for is a brute-force way to compare all subsets
of all possible sizes with other subsets of the same size. I'll leave
that one as an exercise.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,565
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top