2014-01-25 104 views
1

我需要在我的代码中计算一个数组的笛卡尔积,其本身的次数可以变化。例如,如果我的数组是[1,2],我需要填写这些值分为三个插槽,其结果必然是:笛卡尔的力量(笛卡尔乘积与自我任意时间)

[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

您可能正在寻求与重复排列和Ruby的Array从标准库幸运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]] 
+0

谢谢!我以前没有见过这个。 – Phrogz

0

因为我喜欢的monkeypatching,我把这个数组本身:

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

我不知道是否有通过N-1自己的副本的方法更优雅的方式,虽然。

2

你的答案有轻微的变体:

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]] 
+0

啊,我喜欢这一点远远超过' .times.map'。谢谢。 – Phrogz