Combinatorics.jl icon indicating copy to clipboard operation
Combinatorics.jl copied to clipboard

Tuples and Outer

Open lesobrod opened this issue 1 year ago • 1 comments

Hi! I"d like to reproduce next Mathematica functions on Julia: Tuples and Outer
Is it possible with your package, or may be I can add to it?

lesobrod avatar Aug 09 '23 18:08 lesobrod

They can be both implemented with Iterators.product:

tuples(iter, n) = Iterators.product(ntuple(_ -> iter, n)...)
outer(f, iters...) = Iterators.map(args -> f(args...), Iterators.product(iters...))

Example usage:

julia> for t in tuples(1:3, 2) print(t, "  ") end
(1, 1)  (2, 1)  (3, 1)  (1, 2)  (2, 2)  (3, 2)  (1, 3)  (2, 3)  (3, 3)

julia> for o in outer((x,y)->10x+y, 1:2, 4:5) print(o, " ") end
14 24 15 25

Notice that in some cases it can be more convenient to use generators directly

julia> for t in ((x,y) for x in 1:3, y in 1:3) print(t, "  ") end
(1, 1)  (2, 1)  (3, 1)  (1, 2)  (2, 2)  (3, 2)  (1, 3)  (2, 3)  (3, 3)

julia> [(x,y) for x in 1:3, y in 1:3]
3×3 Matrix{Tuple{Int64, Int64}}:
 (1, 1)  (1, 2)  (1, 3)
 (2, 1)  (2, 2)  (2, 3)
 (3, 1)  (3, 2)  (3, 3)

julia> for o in (10x+y for x in 1:2, y in 4:5) print(o, " ") end
14 24 15 25

julia> [10x+y for x in 1:2, y in 4:5]
2×2 Matrix{Int64}:
 14  15
 24  25

FedericoStra avatar Dec 13 '23 09:12 FedericoStra