Module: Combinatorics::Choose::Mixin

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

Overview

Author:

Since:

  • 0.4.0

Instance Method Summary collapse

Instance Method Details

#choose(k) {|combo| ... } ⇒ Enumerator

Get combinations with a specified number of elements from an input set.

Examples:

[1, 2, 3].choose(2).to_a 
# => [#<Set: {1, 2}>, #<Set: {1, 3}>, #<Set: {2, 3}>]

Parameters:

  • k (Fixnum)

    Cardinality of chosen subsets

Yields:

  • (combo)

    The given block will be passed each combination.

Yield Parameters:

  • combo (Array)

    A k-sized combination of elements from the set.

Returns:

  • (Enumerator)

    If no block is given, an Enumerator of the k-sized combinations within the set will be returned.

Raises:

  • (TypeError)

    self must be Enumerable.

See Also:

Since:

  • 0.4.0



37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/combinatorics/choose/mixin.rb', line 37

def choose(k,&block)
  return enum_for(:choose,k) unless block

  unless kind_of?(Enumerable)
    raise(TypeError,"#{inspect} must be Enumerable")
  end

  elements = self.to_a
  elements.uniq!

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