branch14.org

Hello fellow Rubyists,
as of Ruby 1.8.7 this snippet is obsolete. Just use Array#combination(rank).
 1 module SubSet
 2   
 3   # i admit this could definitly be improved
 4   def self.subsets(set, ranks=nil)
 5     ranks ||= 0..set.size
 6     ranks = ranks..ranks unless ranks.is_a?(Range)
 7     sets = all_subsets(set)
 8     sets.select { |s| ranks.include?(s.size) }
 9   end
10   
11   def self.all_subsets(set)
12     return [[]] if set.empty?
13     set = set.clone
14     first = set.shift
15     sets = all_subsets(set)
16     sets.concat(sets.collect { |s| [first] + s })
17     return sets
18   end
19   
20 end

subsets in ruby

  • snippet type: algorithm
  • keywords: subsets
  • language: ruby

this is an althorithm in ruby that calculates every subset of a given set

all snippets