Sha256: 66b00a2a9dd5c70b2e0b8618dc92ff6341e74ad199b75b69fe09b2f22036cace

Contents?: true

Size: 1.87 KB

Versions: 1

Compression:

Stored size: 1.87 KB

Contents

#
# The CartesianProduct module provide methods for the calculation
# of the cartesian producted between two enumberable objects.
#
# It can also be easily mixed in into any enumberable class,
# i.e. any class with Enumerable module mixed in.
# Notice that the names of the methods for mixin are different.
#
# Module:
#   Cartesian::product(foo, bar)
#
# Mixin:
#   foo.cartesian( bar )
#
# The module is automatically mixed in Array class.
#
# == Author
# Adriano MITRE <adriano.mitre@gmail.com>
#
# == Example
#
# as module
#   require 'cartesian'
#   foo = [1, 2]
#   bar = ["a", "b"]
#   Cartesian::product(foo, bar) #=> [[1, "a"], [1, "b"], [2, "a"], [2, "b"]]
# as mixin
#   require 'cartesian'
#   foo = [1, 2]
#   bar = ["a", "b"]
#   foo.cartesian(bar)  #=> [[1, "a"], [1, "b"], [2, "a"], [2, "b"]]

module Cartesian

  # Produces the cartesian product of self and other.
  # The result is an array of pairs (i.e. two-element arrays).
  #
  # cartesian( [1,2], %w(A B) ) #=> [[1, "A"], [1, "B"], [2, "A"], [2, "B"]]
  #
  # or, if mixed in into Array,
  #
  # [1,2].cartesian %w(A B) #=> [[1, "A"], [1, "B"], [2, "A"], [2, "B"]]
  #
  def Cartesian.product(first, second)
    result = []
    first.each do |a|
      second.each do |b|
        result << [a, b]
      end
    end
    result
  end

  # Cartesian.product for mixin.
  #
  def cartesian(other)
    Cartesian.product(self, other)
  end

  # Behaves as product, except for the elements are joined.
  #
  # joined_cartesian( [1,2], %w(A B) ) #=> ["1A", "1B", "2A", "2B"]
  #
  # or, if mixed in into Array,
  #
  # [1,2].joined_cartesian %w(A B) #=> ["1A", "1B", "2A", "2B"]
  #
  def Cartesian.joined_product(first, second)
    product(first, second).map {|pair| pair.join }
  end

  # Cartesian.joined_product for mixin.
  #
  def joined_cartesian(other)
    Cartesian.joined_product(self, other)
  end
end

class Array
  include Cartesian
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
Cartesian-0.1.0 lib/cartesian.rb