I’m working on a problem where I need to create a CartesianProduct class. I should be able to pass this class 2 lists, and then output the Cartesian product (all possible combinations) of these lists.
So far I can create an object out of this class, create all possible combinations, but when I try to output these results to screen I get each item on its own row as if it doesnt realize it is an array.
My code:
class CartesianProduct
include Enumerable
# Your code here
def initialize(a,b)
@output = []
a.each do |x|
b.each do |y|
if !(output.include? [x,y])
output << [x,y]
end
end
end
end
#getter
def output
@output
end
def each
@output.each do |a| puts a end
end
#setter
def output=(a,b)
a.each do |x|
b.each do |y|
if !(output.include? [a,b])
output << [a,b]
end
end
end
end
end
What Im using to test:
c = CartesianProduct.new([:a,:b], [4,5])
=> #<CartesianProduct:0x93569f8 @output=[[:a, 4], [:a, 5], [:b, 4], [:b, 5]]>
Testing is done via the following command: c.each { |elt| puts elt.inspect }
I get:
irb(main):1403:0> c.each { |elt| puts elt.inspect }
a
4
a
5
b
4
b
5
=> [[:a, 4], [:a, 5], [:b, 4], [:b, 5]]
but I should be getting:
# [:a, 4]
# [:a, 5]
# [:b, 4]
# [:b, 5]
My output is not printing the symbols as symbols but rather converting to string, and its print each item on its own line…
This is homework, so I’m not looking for an answer, but a nudge in the right direction would help quite a bit.
EDIT ========================================================================
Changing my definition of each in the class resolved this issue.
def each
@output.map do |x|
yield x
end
end
Changing my definition of each in the class resolved this issue.