I’m simplifying a larger complex problem with the following…
Given three arrays of integers, what’s the most efficient way to return all the possible combinations of each of the elements? Note that each value from each array will always be given in the same position so [A,B,C] would be the same as [C,B,A]. My desired result is an array of arrays with each hash containing a single combination. For example:
Given:
var array1 = [1,2]
var array2 = [a,b]
var array3 = [foo,bar]
The result would be:
[
[1,a,foo],
[2,a,foo],
[1,b,foo],
[2,b,foo],
[1,a,bar],
[2,a,bar],
[1,b,bar],
[2,b,bar]
]
In Python, use itertools.product:
and wrap it in a
listif you need a sequence, not just an iterable.If you want to see how it’s done, this is the “equivalent” code given in the
itertoolsdocs:although that version of the code isn’t particularly efficient.
There is also a Python implementation in the PyPy version of itertools.