ruby-on-rails – 笛卡尔积ruby

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 笛卡尔积ruby前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. class CartesianProduct
  2. include Enumerable
  3. # your code here
  4. end
  5. #Examples of use
  6. c = CartesianProduct.new([:a,:b],[4,5])
  7. c.each { |elt| puts elt.inspect }
  8. # [:a,4]
  9. # [:a,5]
  10. # [:b,4]
  11. # [:b,5]
  12. c = CartesianProduct.new([:a,[])
  13. c.each { |elt| puts elt.inspect }
  14. # (nothing printed since Cartesian product
  15. # of anything with an empty collection is empty)

我是ruby的新手.我理解如何定义笛卡儿积的实例方法,但我对此毫无头绪.我应该如何构造类对象以满足要求.

解决方法

我不会使用一个类,但保持问题的结构,我写道:
  1. class CartesianProduct
  2. include Enumerable
  3.  
  4. def initialize(xs,ys)
  5. @xs = xs
  6. @ys = ys
  7. end
  8.  
  9. def each
  10. return to_enum unless block_given?
  11. @xs.each do |x|
  12. @ys.each { |y| yield [x,y] }
  13. end
  14. end
  15. end

相反,如果懒惰很重要,我只需编写xs.product(ys)或构建我自己的Array#lazy_product(参见本ticket).

猜你在找的Ruby相关文章