Module: Combinatorics::PowerSet::Mixin

Included in:
Array, Set
Defined in:
lib/combinatorics/power_set/mixin.rb

Overview

Author:

Instance Method Summary collapse

Instance Method Details

#powerset {|subset| ... } ⇒ Enumerator Also known as: power_set

Calculates the power-set of an Enumerable object.

Examples:

Power-set on a Set of strings.

Set['abc', 'xyz', '123'].powerset.to_a
# => [#<Set: {}>,
      #<Set: {"123"}>,
      #<Set: {"xyz"}>,
      #<Set: {"abc"}>,
      #<Set: {"xyz", "123"}>,
      #<Set: {"abc", "123"}>,
      #<Set: {"abc", "xyz"}>,
      #<Set: {"abc", "xyz", "123"}>]

Yields:

  • (subset)

    If a block is given, it will be passed each sub-set from the power-set.

Yield Parameters:

  • subset (Array)

    A sub-set from the power-set.

Returns:



31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/combinatorics/power_set/mixin.rb', line 31

def powerset
  return enum_for(:powerset) unless block_given?

  elements = self.to_a
  elements.uniq!

  0.upto(elements.length) do |k|
    elements.combination(k) do |subset|
      yield Set.new(subset)
    end
  end
end