Skip to content

Commit

Permalink
Rewrote cartesian_product to use Array#list_comprehension.
Browse files Browse the repository at this point in the history
  • Loading branch information
postmodern committed Oct 14, 2011
1 parent 9b040c0 commit cecd979
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 25 deletions.
20 changes: 6 additions & 14 deletions lib/combinatorics/cartesian_product/mixin.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
require 'combinatorics/generator'
require 'combinatorics/list_comprehension'

module Combinatorics
module CartesianProduct
Expand Down Expand Up @@ -36,21 +36,13 @@ module Mixin
#
# @see http://en.wikipedia.org/wiki/Cartesian_product
#
def cartesian_product(other)
return enum_for(:cartprod,other) unless block_given?
def cartesian_product(*others,&block)
return enum_for(:cartesian_product,*others) unless block

unless other.kind_of?(Enumerable)
raise(TypeError, 'cartprod requires another Enumerable object')
end
# a single empty Set will result in an empty Set
return nil if (empty? || others.any?(&:empty?))

other.each do |x|
self.each do |y|
z = [y, x]
z.flatten!

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

alias cartprod cartesian_product
Expand Down
22 changes: 11 additions & 11 deletions spec/cartesian_product/mixin_examples.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,22 @@

shared_examples_for "CartesianProduct::Mixin" do
it "the cartprod of any two Set's should return an Enumerator" do
set = subject[]
set = subject[1]
results = set.cartprod(set)

results.should be_kind_of(Enumerator)
end

it "the cartprod of two empty Set's should return an empty Set" do
set = subject[]
results = set.cartprod([[]]).to_a
results = set.cartprod([]).to_a

results.should be_empty
end

it "the cartprod of a single empty set should return an empty Set" do
set = subject[1]
results = set.cartprod([[]]).to_a
set = subject[1,2]
results = set.cartprod([2,3],[]).to_a

results.should be_empty
end
Expand Down Expand Up @@ -49,21 +49,21 @@
set = subject[1, 2]
results = set.cartprod([3, 4]).to_a

results.should =~ [[1, 3], [1, 4], [2, 3], [2, 4]]
results.should =~ [
[1, 3], [1, 4],
[2, 3], [2, 4]
]
end

it "the cartprod of [0, 1] and [[2, 3], [4, 5]] should be [[0, 2, 4], [1, 2, 4], [0, 3, 4], [1, 3, 4], [0, 2, 5], [1, 2, 5], [0, 3, 5], [1, 3, 5]]" do
set1 = subject[0, 1]
set2 = subject[2, 3]
set3 = subject[4, 5]
results = set1.cartprod([set2, set3]).to_a
results = set1.cartprod(set2, set3).to_a

results.should =~ [
[0, 2, 4],
[1, 2, 4],
[0, 3, 4],
[1, 3, 4],
[0, 2, 5]
[0, 2, 4], [0, 2, 5], [0, 3, 4], [0, 3, 5],
[1, 2, 4], [1, 2, 5], [1, 3, 4], [1, 3, 5],
]
end

Expand Down

0 comments on commit cecd979

Please sign in to comment.