Get Version

0.6.7

cartesian

Cartesian products in Ruby

What

Provides methods for the calculation of the cartesian producted between
two or more enumerable objects. Includes grid search optimization methods.
It can also be easily and conveniently mixed-in into any enumerable class.

Installing

sudo gem install cartesian

The basics

Cartesian::product [1,2],[3,4] #=> [[1, 3], [1, 4], [2, 3], [2, 4]]

Demonstration of usage

One can use the Cartesian module directly

require 'cartesian'
foo = [1, 2]
bar = ["a", "b"]
Cartesian::product(foo, bar) #=> [[1, "a"], [1, "b"], [2, "a"], [2, "b"]]

or use the methods provided by the mixin in the Array class

foo.cartesian(bar)  #=> [[1, "a"], [1, "b"], [2, "a"], [2, "b"]]

which include the short’n’sweet x method

v = [] #=> []
for a, b in [1,2].x [3,4]
  v << [a,b]
end #=> true
v #=> [[1, 3], [1, 4], [2, 3], [2, 4]]

The ‘**’ operator provides a convenient way of iterating multi-dimensionally over the same array or range

u = [0, 1]**3 #=> #<CartesianIterator:0x7f2fb8e54978 @tot_iter=8, \
  #                @lists=[[0, 1], [0, 1], [0, 1]]>
u.to_a #=> [[0, 0, 0], [0, 0, 1], [0, 1, 0], \
  #        [0, 1, 1], [1, 0, 0], [1, 0, 1], \
  #        [1, 1, 0], [1, 1, 1]]

Finally, the grid search methods

require 'grid_search'
[-1, 0, 1, 2].argmax {|x| x**2 } #=> 2
[-1, 0, 1, 2].argmin {|x| x.abs } #=> 0

For more examples and details, see the RDoc-generated documentation here.

How to submit patches

Read the 8 steps for fixing other people’s code and for section 8b: Submit patch to Google Groups, use the Google Group above.

You can fetch the source from:

git clone git@github.com:adrianomitre/cartesian.git

Build and test instructions

cd cartesian
rake test
rake install_gem

License

This code is free to use under the terms of the MIT license.

Contact

Comments are welcome. Send an email to Adriano Mitre.

Adriano Mitre, 7th January 2011
Theme extended from Paul Battley