How to get all combinations from multiple input arrays?


Say I have three input arrays like the ones below (could be arbitrary amount) and I want to generate all possible combinations of values with one entry from each array. The existing functions in Combinatorics.jl only work with one array (e.g. [:a, 1, “hi”], [:a,1,“bye”], [:a,2,“hi”]). If I knew I would always have three arrays I could just loop but I do not know beforehand if I will have 2 or 3 or 4 etc arrays to generate combinations from. Is there any way to do this that I’m just missing or some package I don’t know of?


letters = [:a, :b, :c]
numbers = [1,2,3]
other = ["hi", "bye"]
julia> allcombinations(v...) = vec(collect(Iterators.product(v...)))
allcombinations (generic function with 1 method)

julia> allcombinations(letters, numbers, other)
18-element Vector{Tuple{Symbol, Int64, String}}:
 (:a, 1, "hi")
 (:b, 1, "hi")
 (:c, 1, "hi")
 (:a, 2, "hi")
 (:b, 2, "hi")
 (:c, 2, "hi")
 (:a, 3, "hi")
 (:b, 3, "hi")
 (:c, 3, "hi")
 (:a, 1, "bye")
 (:b, 1, "bye")
 (:c, 1, "bye")
 (:a, 2, "bye")
 (:b, 2, "bye")
 (:c, 2, "bye")
 (:a, 3, "bye")
 (:b, 3, "bye")
 (:c, 3, "bye")
1 Like

Thank you!

Note that you generally want to avoid collect which materialises the iterator if you can avoid it.

1 Like