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

Discussion in 'Ruby' started by Shreyas Satish, Apr 6, 2010.

  1. 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.
    Shreyas Satish, Apr 6, 2010
    1. Advertisements

  2. Hello,

    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.


    JJ Fleck
    PCSI1 Lyc=E9e Kl=E9ber
    Jean-Julien Fleck, Apr 6, 2010
    1. Advertisements

  3. Well, the way to get common elements between arrays is with the
    "intersection" method: (of course,
    available as a Set operation too:

    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.
    Aldric Giacomoni, Apr 6, 2010
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.