循环排列

时间:2017-03-26 22:02:01

标签: julia permutation

给定一个向量override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent) { //you can't pass the sender so couldn't call your showUserLocation action function, //so move implementation of showUserLocation to showUserLocationHelper and now you can do what you need after shake event showUserLocationHelper() } // Showing the user location //this is an action function for some UI element like a UIButton and the sender is required to be passed for this function to fire thus, motionEnded cannot directly call it //but you do not use sender at all func showUserLocation(sender : AnyObject) { showUserLocationHelper() } func showUserLocationHelper() { let status = CLLocationManager.authorizationStatus() //Asking for authorization to display current location if status == CLAuthorizationStatus.NotDetermined { locationManager.requestWhenInUseAuthorization() } else { locationManager.startUpdatingLocation() } } ,我想创建一个向量向量,其所有循环排列为z = [1, 2, 3](即z)。

我可以使用

打印zp = [[1,2,3], [3,1,2], [2,3,1]]的所有元素
zp

如何存储产生的排列?注意

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

无效,因为它在zp = Vector(length(z)) for i in 1:length(z) push!(z, shift!(z)) push!(zp, z) end 中存储了相同的向量z 3次。

2 个答案:

答案 0 :(得分:6)

一种方法就是在推送之前复制矢量:

z = [1, 2, 3];

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

给了我

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

但我倾向于在可以的时候避免变异操作。所以我把它写成

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]

答案 1 :(得分:3)

这似乎在我的机器上执行得非常快(比理解更快):

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>