如何用Ruby编写笛卡尔积?

时间:2013-04-06 20:43:19

标签: ruby arrays cartesian-product

http://spark-university.s3.amazonaws.com/berkeley-saas/homework/hw1.pdf

尝试完成此作业的第7部分。以下代码似乎不起作用,但坦率地说我不知道​​为什么,自动分级器会留下代码后面的注释。

class CartesianProduct
    include Enumerable

    def initialize(arr1 = [], arr2 = [])
        @arr1 = arr1
        @arr2 = arr2
    end

    def each
        prod = []
        @arr1.each do |i|
            @arr2.each do |j|
                prod << [i, j]
            end
        end
        prod.each
    end
end

On Time 
CartesianProduct

Failures:

  1) CartesianProduct should work for the first example given in the homework [15 points]
     Failure/Error: c.to_a.should include([:a, 4],[:a,5],[:b,5],[:b,4])
       expected [] to include [:a, 4], [:a, 5], [:b, 5], and [:b, 4]
       Diff:
       @@ -1,2 +1,2 @@
       -[[:a, 4], [:a, 5], [:b, 5], [:b, 4]]
       +[]

  2) CartesianProduct should work for other examples for 2x2 [20 points]
     Failure/Error: c.to_a.should include([11, 13],[11, 14],[12, 13],[12, 14])
       expected [] to include [11, 13], [11, 14], [12, 13], and [12, 14]
       Diff:
       @@ -1,2 +1,2 @@
       -[[11, 13], [11, 14], [12, 13], [12, 14]]
       +[]

  3) CartesianProduct should work for 3x3 and 4x4 [40 points]
     Failure/Error: c.to_a.should include([1, 4],[1, 5],[1, 6],[2, 4],[2, 5],[2, 6],[3, 4],[3, 5],[3, 6])
       expected [] to include [1, 4], [1, 5], [1, 6], [2, 4], [2, 5], [2, 6], [3, 4], [3, 5], and [3, 6]
       Diff:
       @@ -1,2 +1,2 @@
       -[[1, 4], [1, 5], [1, 6], [2, 4], [2, 5], [2, 6], [3, 4], [3, 5], [3, 6]]
       +[]

Finished in 0.00631 seconds
5 examples, 3 failures

Failed examples:

rspec /tmp/rspec20130406-910-bhzxkp.rb:32 # CartesianProduct should work for the first example given in the homework [15 points]
rspec /tmp/rspec20130406-910-bhzxkp.rb:47 # CartesianProduct should work for other examples for 2x2 [20 points]
rspec /tmp/rspec20130406-910-bhzxkp.rb:55 # CartesianProduct should work for 3x3 and 4x4 [40 points]

有人可以向我解释错误是什么,所以我可以在我的代码中修复它们吗?我是Ruby的新手,所以我实际上不确定自动评分者说的是什么......

一些示例输入和输出: [:a,:b,:c],[4,5]#=&gt; [[:a,4],[:a,5],[:b,4],[:b,5],[:c,4],[:c,5]] 对于这种情况,我的代码可以工作。

2 个答案:

答案 0 :(得分:14)

使用Array#product

p [:a, :b, :c].product [4, 5]

<强>输出:

[[:a, 4], [:a, 5], [:b, 4], [:b, 5], [:c, 4], [:c, 5]]

答案 1 :(得分:3)

您的每个实施都有问题。您在对数组上调用每个对,但是您没有通过传递给每个方法的块。解决这个问题的一种方法是将您的方法定义为

def each(&block)
  #setup prod
  prod.each(&block)
end

将块传递给您的每个方法,并确保在您计算的产品数组上调用每个方法时也使用它