day*_*ter 7 arrays iteration julia
我有一个简单的问题应该有一个简单的答案,但我还没想到它.我想一次处理一个数组,一定数量的元素,然后回绕到开头.
这是一个图表,显示n每次需要10和3个元素时:
到目前为止,我尝试编写一个简单的迭代失败了:使用% n给我零,这不适用于Julia的一个索引...... :)
Fen*_*ang 10
mod1提供该功能是为了实现您想要的行为:
julia> mod1(1, 5)
1
julia> mod1(3, 5)
3
julia> mod1(5, 5)
5
julia> mod1(6, 5)
1
Run Code Online (Sandbox Code Playgroud)
制作mod-indexed函数非常简单:
modindex(A, i) = A[mod1(i, length(A))]
Run Code Online (Sandbox Code Playgroud)
甚至你自己的mod索引数组类型:
julia> immutable CircArray{T} <: AbstractArray{T,1}
xs::Vector{T}
end
julia> Base.size(x::CircArray) = (length(x.xs),)
julia> Base.getindex(x::CircArray, i) = x.xs[mod1(i, length(x.xs))]
julia> A = CircArray([1:2:10;])
CircArray{Array{Int64,1}}([1,3,5,7,9])
julia> A[0]
9
julia> A[5]
9
julia> A[7]
3
Run Code Online (Sandbox Code Playgroud)
在此基础上实现切片并不太难.正如DNF在评论中提到的那样,一个简洁明了的解决方案就是
modindex(A, i) = A[mod1.(i, end)]
Run Code Online (Sandbox Code Playgroud)
或等效的getindex,处理标量索引和切片.
编辑:由于你的问题提到迭代,我想我会提供一个更通用的解决方案,也可以在非数组上用于迭代目的,只使用以下功能性迭代Base:
julia> threes(A) = let cy = cycle(A)
take(zip(cy, drop(cy, 1), drop(cy, 2)), length(A))
end
threes (generic function with 1 method)
julia> for (a, b, c) in threes([1, 2, 3, 4, 5])
println(a, b, c)
end
123
234
345
451
512
Run Code Online (Sandbox Code Playgroud)