logankilpatrick
logankilpatrick

Reputation: 14551

How to generate all permutations of an array in Julia?

Given I have some array:

julia> a = [1, 2, 3]
3-element Vector{Int64}:
 1
 2
 3

how can I generate all of its permutations? I am happy to write this by hand but would also be interested in a built in function which is performant.

Upvotes: 3

Views: 1951

Answers (1)

logankilpatrick
logankilpatrick

Reputation: 14551

In Julia, you can use the Combinatorics package to do the following:

julia> using Combinatorics

julia> b = permutations(a)
Combinatorics.Permutations{Vector{Int64}}([1, 2, 3], 3)

julia> for item in b
           print(item)
       end
[1, 2, 3][1, 3, 2][2, 1, 3][2, 3, 1][3, 1, 2][3, 2, 1]

You can read more about the permutations function in the Combinatorics docs.

Upvotes: 3

Related Questions