笛卡尔积

实现一

module Enumerable
  def cartesian(other)
    res = []
    each { |x| other.each { |y| res << [x, y]}}
    return res
  end
end

 

实现二

module Enumerable
  def cartesian(other)
    inject([]) { |res, x| other.inject(res) { |res, y| res << [x, y] } }
  end
end

 

示例

p [1, 2, 3].cartesian(["a", "b", "c"])
[[1, "a"], [1, "b"], [1, "c"], [2, "a"], [2, "b"], [2, "c"], [3, "a"], [3, "b"], [3, "c"]]

 

实现二的代码更简洁,但实现一的代码更高效。

你可能感兴趣的:(C++,c,C#)