graphtheory123
graphtheory123

Reputation: 307

How to do a cartesian product of a variable number of lists in Julia?

For each value j in the set {1, 2, ..., n} where the value of n can vary (it is some variable in my program that can be different depending on the inputs from the user), I have an array A_j. I would like to obtain the cartesian product of all the arrays A_j, so that I can then iterate through that cartesian product (taking one element from each A_1, A_2, ... A_n to get a tuple (a_1, a_2, ..., a_n) in A_1 x A_2 x ... x A_n). How would I accomplish this in Julia?

Upvotes: 2

Views: 601

Answers (1)

Vincent Yu
Vincent Yu

Reputation: 488

Use Iterators.product:

help?> Iterators.product
  product(iters...)

  Return an iterator over the product of several iterators. Each generated
  element is a tuple whose ith element comes from the ith argument iterator.
  The first iterator changes the fastest.

  Examples
  ≡≡≡≡≡≡≡≡≡≡

  julia> collect(Iterators.product(1:2, 3:5))
  2×3 Matrix{Tuple{Int64, Int64}}:
   (1, 3)  (1, 4)  (1, 5)
   (2, 3)  (2, 4)  (2, 5)

Upvotes: 5

Related Questions