Sha256: 2f6336bcfc8cb6d2f0115d962841e254fa1a64d6c631b79e3ae3b3b5df99a304
Contents?: true
Size: 1.33 KB
Versions: 3
Compression:
Stored size: 1.33 KB
Contents
module Combinatorics module PowerSet module Mixin # # Calculates the power-set of an Enumerable object. # # @yield [subset] # If a block is given, it will be passed each sub-set from the # power-set. # # @yieldparam [Array] subset # A sub-set from the power-set. # # @return [Array] # The power set. # # @example Power-set of an Array. # [1,2,3].powerset # # => [[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]] # # @example Power-set on a Set of strings. # Set['abc', 'xyz', '123'].powerset # # => [#<Set: {}>, #<Set: {"123"}>, #<Set: {"xyz"}>, # #<Set: {"abc"}>, #<Set: {"xyz", "123"}>, # #<Set: {"abc", "123"}>, #<Set: {"abc", "xyz"}>, # #<Set: {"abc", "xyz", "123"}>] # # @see http://johncarrino.net/blog/2006/08/11/powerset-in-ruby/ # def powerset inject([self.class.new]) do |power_set,element| sub_set = [] power_set.each do |previous_set| new_set = previous_set + [element] yield new_set if block_given? sub_set << previous_set sub_set << new_set end sub_set end end alias cartesian_product powerset end end end
Version data entries
3 entries across 3 versions & 1 rubygems
Version | Path |
---|---|
combinatorics-0.3.1 | lib/combinatorics/power_set/mixin.rb |
combinatorics-0.3.0 | lib/combinatorics/power_set/mixin.rb |
combinatorics-0.2.0 | lib/combinatorics/power_set/mixin.rb |