Module: Combinatorics::CartesianProduct::Mixin

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

Overview

Author:

Since:

  • 0.4.0

Instance Method Summary collapse

Instance Method Details

#cartesian_product(*others) {|subset| ... } ⇒ Enumerator Also known as: cartprod, cartesian

Calculates the Cartesian product of an Enumerable object.

Examples:

Cartesian product of an Array

[1, 2].cartesian_product([3, 4])
# => [[1, 3], [2, 3], [1, 4], [2, 4]]

Cartesian product over an Array of Strings

['a'].cartesian_product(['b', 'c', 'd']).to_a
# => [["a", "b"], ["a", "c"], ["a", "d"]]

Three-way Cartesian product operation

[0, 1].cartesian_product([2, 3], [4, 5]).to_a
# => [
#      [0, 2, 4], [0, 2, 5], [0, 3, 4], [0, 3, 5],
#      [1, 2, 4], [1, 2, 5], [1, 3, 4], [1, 3, 5],
#    ]

Yields:

  • (subset)

    If a block is given, it will be passed each individual subset element from the Cartesian product set as a whole.

Yield Parameters:

  • subset (Array)

    The sub-set from the Cartesian product.

Returns:

  • (Enumerator)

    Resulting Cartesian product set.

Raises:

  • (TypeError)

    other must be Enumerable.

See Also:

Since:

  • 0.4.0



46
47
48
49
50
51
52
53
# File 'lib/combinatorics/cartesian_product/mixin.rb', line 46

def cartesian_product(*others,&block)
  return enum_for(:cartesian_product,*others) unless block

  # a single empty Set will result in an empty Set
  return nil if (empty? || others.any?(&:empty?))

  Array[self,*others].comprehension(&block)
end