Cartesian power (cartesian product with self arbitrary times)

孤街浪徒 提交于 2019-12-11 13:52:51

问题


I have a need in my code to calculate the cartesian product of an array with itself a varying number of times. For example, if my array is [1,2] and I need to fill these values into three slots, the result would be:

[1,1,1]
[1,1,2]
[1,2,1]
[1,2,2]
[2,1,1]
[2,1,2]
[2,2,1]
[2,2,2]

What's the easiest way to do this?


回答1:


You are probably looking for permutation with repetition and Ruby's Array from standard library luckily implements this:

[1,2].repeated_permutation(3).to_a
# [[1, 1, 1], [1, 1, 2], [1, 2, 1], [1, 2, 2], [2, 1, 1], [2, 1, 2], [2, 2, 1], [2, 2, 2]]



回答2:


A slight variant of your answer:

class Array
  def **(n)
    product( *([self]*(n-1)) )
  end
end

[1,2]**3
  # => [[1, 1, 1], [1, 1, 2], [1, 2, 1], [1, 2, 2],
  #     [2, 1, 1], [2, 1, 2], [2, 2, 1], [2, 2, 2]] 



回答3:


Because I like monkeypatching, I put this on the array itself:

class Array
  def **(n)
    self.product( *(n-1).times.map{ self } )
  end
end

I'm not sure if there's a more elegant way to pass n-1 copies of yourself to the method, though.



来源:https://stackoverflow.com/questions/21347083/cartesian-power-cartesian-product-with-self-arbitrary-times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!