【问题标题】:How to write Cartesian Product in Ruby?如何用 Ruby 编写笛卡尔积?
【发布时间】:2013-03-29 03:51:20
【问题描述】:

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

尝试完成此作业的第 7 部分。以下代码似乎不起作用,但坦率地说,我不确定为什么,自动评分器会留下代码后面的 cmets。

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] ] 对于这种情况,我的代码有效。

【问题讨论】:

  • 只给一个输入和输出..就是这样。
  • 问题是我看不懂哪个是哪个...
  • 这就是为什么告诉我 i/p 和预期输出,我会帮助你
  • 我添加了一个案例,但我的代码适用于那个案例

标签: ruby arrays cartesian-product


【解决方案1】:

使用Array#product

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

输出:

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

【讨论】:

  • 那段 sn-p 代码仍然无法与自动评分器一起使用,不知道为什么
  • @user1796994 什么是自动评分器?
  • 哦,它基本上用各种情况测试我的代码,它的 cmets 是粘贴在问题中的内容。 Array#product 解决方案和我最初的解决方案都不完全有效。
【解决方案2】:

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

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

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

【讨论】:

    猜你喜欢
    • 2021-07-17
    • 2017-02-09
    • 2021-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-15
    • 1970-01-01
    相关资源
    最近更新 更多