Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative to nested for-loop in Julia

Given arbitrary integers a and b, I want to create a list of all different pairs within Z_a^b \times Z_a^b. For example, taking a=3 and b=2, I want to have an array

[[[0,0],[0,0]],[[0,0],[0,1]],[[0,0],[0,2]],...,[[2,2],[2,1]],[[2,2],[2,2]]] 

I want to do this within Julia. However, I do not know how to do this easily for arbitrary values of b (even for fixed b, the only way I can think to do this would be nested for loops). Is there a quick way of implementing this?

like image 859
Joshuah Heath Avatar asked May 07 '26 23:05

Joshuah Heath


1 Answers

Is this what you want?

julia> Z(a, b) = Iterators.product([0:a-1 for _ in 1:b]...)
Z (generic function with 1 method)

julia> collect(Iterators.product(Z(3,2), Z(3,2))) |> vec
81-element Vector{Tuple{Tuple{Int64, Int64}, Tuple{Int64, Int64}}}:
 ((0, 0), (0, 0))
 ((1, 0), (0, 0))
 ((2, 0), (0, 0))
 ((0, 1), (0, 0))
 ((1, 1), (0, 0))
 ((2, 1), (0, 0))
 ((0, 2), (0, 0))
 ((1, 2), (0, 0))
 ((2, 2), (0, 0))
 ((0, 0), (1, 0))
 ⋮
 ((0, 0), (2, 2))
 ((1, 0), (2, 2))
 ((2, 0), (2, 2))
 ((0, 1), (2, 2))
 ((1, 1), (2, 2))
 ((2, 1), (2, 2))
 ((0, 2), (2, 2))
 ((1, 2), (2, 2))
 ((2, 2), (2, 2))

julia> collect(Iterators.product(Z(4,3), Z(4,3))) |> vec
4096-element Vector{Tuple{Tuple{Int64, Int64, Int64}, Tuple{Int64, Int64, Int64}}}:
 ((0, 0, 0), (0, 0, 0))
 ((1, 0, 0), (0, 0, 0))
 ((2, 0, 0), (0, 0, 0))
 ((3, 0, 0), (0, 0, 0))
 ((0, 1, 0), (0, 0, 0))
 ((1, 1, 0), (0, 0, 0))
 ((2, 1, 0), (0, 0, 0))
 ((3, 1, 0), (0, 0, 0))
 ((0, 2, 0), (0, 0, 0))
 ((1, 2, 0), (0, 0, 0))
 ⋮
 ((3, 1, 3), (3, 3, 3))
 ((0, 2, 3), (3, 3, 3))
 ((1, 2, 3), (3, 3, 3))
 ((2, 2, 3), (3, 3, 3))
 ((3, 2, 3), (3, 3, 3))
 ((0, 3, 3), (3, 3, 3))
 ((1, 3, 3), (3, 3, 3))
 ((2, 3, 3), (3, 3, 3))
 ((3, 3, 3), (3, 3, 3))

Note that I collect it to make the result visible. Normally, as the result set can be very large it is better to stay with lazy Iterators.product and just iterate it.

like image 94
Bogumił Kamiński Avatar answered May 11 '26 02:05

Bogumił Kamiński