定义代码
struct Paths
m::Int
n::Int
end
Base.iterate(p::Paths) = fill(1,p.m), fill(1,p.m) #start the iteration with 1's
Base.IteratorSize(::Type{Paths}) = SizeUnknown()
function Base.iterate(p::Paths, state)
if state ≠ fill(p.n,p.m) # end when each row has an n
newstate = next(state,p.n)
return newstate, newstate
end
end
function next(path,n)
k = length(path)
# start from the end and find the first element that can be updated by adding 1
while k≥2 && ( path[k]==n || path[k]+1 > path[k-1]+1 )
k -= 1
end
path[k] +=1 #add the one then reset the following elements
for j = k+1 : length(path)
path[j] = max(path[j-1]-1,1)
end
return(path)
end
function allpaths(m,n)
v=Vector{Int}[]
paths = Paths(m,n)
for p ∈ paths
push!(v,copy(p))
end
v
end
调用代码
let
paths1=Paths(6,6)
v=Vector{Int}[]
for p in paths1
push!(v, copy(p))
end
length(v), v
end
问题1:调用函数中为什么用copy函数,如果不用copy函数结果只包含两种类型,length(v)=950, v=[[1,1,1,1,1,1],[6,6,6,6,6,6],[6,6,6,6,6,6]…];如果用copy函数则结果正常。
问题2:next函数中,while循环中 ( path[k]==n || path[k]+1 > path[k-1]+1 ),条件中大于号为什么要同时加上1, 感觉这样做无意义。另外为什么需要这个守卫条件不是很理解。