2

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] #=> [ [:a,4], [:a,5], [:b,4], [:b ,5], [:c,4], [:c,5] ] 对于这种情况,我的代码有效。

4

2 回答 2

14

采用Array#product

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

输出:

[[:a, 4], [:a, 5], [:b, 4], [:b, 5], [:c, 4], [:c, 5]]
于 2013-04-06T21:07:28.773 回答
3

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

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

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

于 2013-04-06T21:32:50.550 回答