amrods
amrods

Reputation: 2131

Circular permutations

Given a vector z = [1, 2, 3], I want to create a vector of vectors with all circular permutations of z (i.e. zp = [[1,2,3], [3,1,2], [2,3,1]]).

I can print all elements of zp with

for i in 1:length(z)
    push!(z, shift!(z)) |> println
end

How can I store the resulting permutations? Note that

zp = Vector(length(z))
for i in 1:length(z)
    push!(z, shift!(z))
    push!(zp, z)
end

doesn't work as it stores the same vector z 3 times in zp.

Upvotes: 3

Views: 903

Answers (2)

rickhg12hs
rickhg12hs

Reputation: 11932

This seems to execute pretty quick on my machine (faster than a comprehension):

julia> z=[1,2,3]
3-element Array{Int64,1}:
 1
 2
 3

julia> zp=Vector{typeof(z)}(length(z))
3-element Array{Array{Int64,1},1}:
 #undef
 #undef
 #undef

julia> for i=1:length(z)
         zp[i]=circshift(z,i-1)
       end

julia> zp
3-element Array{Array{Int64,1},1}:
 [1,2,3]
 [3,1,2]
 [2,3,1]

julia> 

Upvotes: 4

DSM
DSM

Reputation: 353359

One way would just be to copy the vector before pushing it:

z = [1, 2, 3];

zp = Vector();
for i in 1:length(z)
    push!(z, shift!(z))
    push!(zp, copy(z))
end

gives me

julia> zp
3-element Array{Any,1}:
 [2,3,1]
 [3,1,2]
 [1,2,3]

But I tend to prefer avoiding mutating operations when I can. So I'd instead write this as

julia> zp = [circshift(z, i) for i=1:length(z)]
3-element Array{Array{Int64,1},1}:
 [3,1,2]
 [2,3,1]
 [1,2,3]

Upvotes: 7

Related Questions