JuliaMath / Combinatorics.jl

A combinatorics library for Julia
http://juliamath.github.io/Combinatorics.jl/dev/
Other
214 stars 58 forks source link

Tuples and Outer #140

Open lesobrod opened 1 year ago

lesobrod commented 1 year ago

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?

FedericoStra commented 8 months ago

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