问题
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