Skip to content

Commit 33bcbfb

Browse files
committed
Minimal fix for ncpartitions
Fixes #9
1 parent 3da9f40 commit 33bcbfb

File tree

2 files changed

+39
-23
lines changed

2 files changed

+39
-23
lines changed

src/partitions.jl

Lines changed: 30 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -416,28 +416,35 @@ end
416416
#Noncrossing partitions
417417

418418
#Produces noncrossing partitions of length n
419-
ncpartitions(n::Integer)=ncpart(1,n,n,Any[])
420-
function ncpart(a::Integer, b::Integer, nn::Integer,
421-
x::Array{Any,1})
422-
n=b-a+1
423-
for k=1:n
424-
for root in @task cool_lex(n, k)
425-
root += a-1
426-
#Abort if construction is out of lex order
427-
if length(x)>0 && x[end] > root return end
428-
#Produce if we've filled all the holes
429-
sofar = Any[x..., root]
430-
ssofaru = sort(union(sofar...))
431-
if length(ssofaru)==nn && ssofaru==[1:nn]
432-
produce(sofar)
433-
return
434-
end
435-
#otherwise patch all remaining holes
436-
blob = [ssofaru; nn+1]
437-
for l=1:length(blob)-1
438-
ap, bp = blob[l]+1, blob[l+1]-1
439-
if ap <= bp ncpart(ap, bp, nn, sofar) end
440-
end
419+
function ncpartitions(n::Int)
420+
partitions = Vector{Vector{Int}}[]
421+
_ncpart!(1,n,n,Vector{Int}[], partitions)
422+
partitions
423+
end
424+
425+
function _ncpart!(a::Int, b::Int, nn::Int,
426+
x::Vector, partitions::Vector)
427+
428+
n=b-a+1
429+
for k=1:n, root in CoolLexCombinations(n, k)
430+
root += a-1
431+
#Abort if construction is out of lex order
432+
if !isempty(x) && lexcmp(x[end], root)==1 return end
433+
434+
#Save if we've filled all the holes
435+
sofar = Vector{Int}[x..., root]
436+
ssofaru = sort(union(sofar...))
437+
if length(ssofaru)==nn && ssofaru==collect(1:nn)
438+
push!(partitions, sofar)
439+
return
440+
end
441+
442+
#otherwise patch all remaining holes
443+
blob = [ssofaru; nn+1]
444+
for l=1:length(blob)-1
445+
ap, bp = blob[l]+1, blob[l+1]-1
446+
if ap <= bp _ncpart!(ap, bp, nn, sofar, partitions) end
447+
end
441448
end
442-
end
443449
end
450+

test/partitions.jl

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,3 +28,12 @@ import Combinatorics: partitions, prevprod
2828
@test prevprod([2,3,5],30) == 30
2929
@test prevprod([2,3,5],33) == 32
3030

31+
# noncrossing partitions
32+
let nc4 = ncpartitions(4)
33+
@test nc4 == Any[Any[[1],[2],[3],[4]], Any[[1],[2],[3,4]], Any[[1],[2,3],[4]], Any[[1],[2,4],[3]], Any[[1],[2,3,4]],
34+
Any[[1,2],[3],[4]], Any[[1,2],[3,4]],
35+
Any[[1,3],[2],[4]], Any[[1,4],[2],[3]], Any[[1,4],[2,3]],
36+
Any[[1,2,3],[4]], Any[[1,3,4],[2]], Any[[1,2,4],[3]],
37+
Any[[1,2,3,4]]]
38+
@test length(nc4) == catalannum(4)
39+
end

0 commit comments

Comments
 (0)