On Jan 26, 6:05 am, Thomas Hafner <tho...@hafner.NL.EU.ORG> wrote:
> Hello,
> did I miss some standard library function? Anyway, then I'll do it on
> my own:
> def cartprod(*args)
> result = []
> while != args
> t, result = result,
> b, *args = args
> t.each do |a|
> b.each do |n|
> result << a + [n]
> end
> end
> end
> result
> end
> Example:
> cartprod([1,2],[3,4,5],[6,7,8])
> => [[1, 3, 6], [1, 3, 7], [1, 3, 8], [1, 4, 6], [1, 4, 7], [1, 4, 8],
> [1, 5, 6], [1, 5, 7], [1, 5, 8], [2, 3, 6], [2, 3, 7], [2, 3, 8],
> [2, 4, 6], [2, 4, 7], [2, 4, 8], [2, 5, 6], [2, 5, 7], [2, 5, 8]]Hi--
I was going to say that Facets has cross:
require 'facets/core/enumerable/cross'
Enumerable.cross([1,2],[3,4,5],[6,7,8])
=> [[1, 3, 6], [1, 3, 7], [1, 3, 8], [1, 4, 6], [1, 4, 7], [1, 4,
8], [1, 5, 6], [1, 5, 7], [1, 5, 8], [2, 3, 6], [2, 3, 7], [2, 3, 8],
[2, 4, 6], [2, 4, 7], [2, 4, 8], [2, 5, 6], [2, 5, 7], [2, 5, 8]]
Also when just deailing with a pair:
require 'facets/core/enumerable/op_pow'
[1,2] ** [3,4,5]
=> [[1, 3], [1, 4], [1, 5], [2, 3], [2, 4], [2, 5]]
there are two considerations though: 1) your implementation retains an
additional array level for each initial possibility. is that desired
behavior?