On Wed, Nov 4, 2009 at 4:19 PM, George George <george.githinji / gmail.com> wrote:
> Given an array of arrays for example
> [["A", "B"], ["A", "B", "D", "C"], ["B", "D"], ["B", "C", "F", "E"],
> ["C", "F"], ["C", "E"], ["G"]]
>
> what would be a nice way of "merging" the items that seem to already be
> contained in another array. e.g.
> ["A","B"] and ["B", "D"] are subsets of ["A", "B", "D", "C"] I would
> like to drop the subsets      ۢ¢ Ģ â 
Here are two ways:

require 'set'

# --------------------------------------------------------------
# method 1:

sets = [["A", "B"], ["A", "B", "D", "C"], ["B", "D"], ["B", "C", "F",
"E"], ["C", "F"], ["C", "E"], ["G"]]

sets = sets.map {|x| x.to_set}.sort_by {|x| -x.size}

(0...(sets.length)).each do |i|
  next unless sets[i]
  ((i+1)...(sets.length)).each do |j|
    sets[j] = nil if sets[j] && sets[j].subset?(sets[i])
  end
end

sets = sets.compact.map {|x| x.to_a}
p sets

# --------------------------------------------------------------
# method 2:

sets = [["A", "B"], ["A", "B", "D", "C"], ["B", "D"], ["B", "C", "F",
"E"], ["C", "F"], ["C", "E"], ["G"]]

sets = sets.map {|x| x.to_set}.sort_by {|x| -x.size}

i = 0
while i < sets.length
  ((i+1)...(sets.length)).each do |j|
    sets[j] = nil if sets[j].subset?(sets[i])
  end
  sets.compact!
  i += 1
end

sets = sets.map {|x| x.to_a}
p sets

martin