diff --git a/src/partitions.jl b/src/partitions.jl index 9ba2969..9184fb1 100644 --- a/src/partitions.jl +++ b/src/partitions.jl @@ -17,7 +17,12 @@ end Base.length(p::IntegerPartitions) = npartitions(p.n) Base.eltype(p::IntegerPartitions) = Vector{Int} -function Base.iterate(p::IntegerPartitions, xs = Int[]) +function Base.iterate(p::IntegerPartitions) + p.n == 0 && return (Int[], Int[]) + return iterate(p, Int[]) +end + +function Base.iterate(p::IntegerPartitions, xs) length(xs) == p.n && return xs = nextpartition(p.n,xs) (xs, xs) @@ -31,7 +36,10 @@ large, this function returns an iterator object. Use `collect(partitions(n))` to array of all partitions. The number of partitions to generate can be efficiently computed using `length(partitions(n))`. """ -partitions(n::Integer) = IntegerPartitions(n) +function partitions(n::Integer) + n<0 && throw(DomainError(n, "n must be nonnegative")) + return IntegerPartitions(n) +end @@ -344,6 +352,9 @@ function nfixedsetpartitions(n::Int, m::Int) return numpart end +# This should maybe be depricated. But for now it's updated +integer_partitions(n::Int) = collect(partitions(n)) + # TODO: Base.DSP is no longer a thing in Julia 0.7 #This function is still defined in Base because it is being used by Base.DSP #""" @@ -442,39 +453,6 @@ function prevprod(a::Vector{Int}, x) return Int(best) end - -""" - integer_partitions(n) - -List the partitions of the integer `n`. - -!!! note - The order of the resulting array is consistent with that produced by the computational - discrete algebra software GAP. -""" -function integer_partitions(n::Integer) - if n < 0 - throw(DomainError(n, "n must be nonnegative")) - elseif n == 0 - return Vector{Int}[] - elseif n == 1 - return Vector{Int}[[1]] - end - - list = Vector{Int}[] - - for p in integer_partitions(n-1) - push!(list, [p; 1]) - if length(p) == 1 || p[end] < p[end-1] - push!(list, [p[1:end-1]; p[end]+1]) - end - end - - list -end - - - #Noncrossing partitions const _cmp = cmp diff --git a/test/partitions.jl b/test/partitions.jl index 7c068c3..cfca9bb 100644 --- a/test/partitions.jl +++ b/test/partitions.jl @@ -19,15 +19,14 @@ @test isa(collect(partitions([1,2,3,4], 3)), Vector{Vector{Vector{Int}}}) @test length(partitions(0)) == 1 -@test length(partitions(-1)) == 0 @test length(collect(partitions(30))) == length(partitions(30)) @test length(collect(partitions(90,4))) == length(partitions(90,4)) @test length(collect(partitions('a':'h'))) == length(partitions('a':'h')) @test length(collect(partitions('a':'h',5))) == length(partitions('a':'h',5)) # integer_partitions -@test integer_partitions(0) == [] -@test integer_partitions(5) == Any[[1, 1, 1, 1, 1], [2, 1, 1, 1], [2, 2, 1], [3, 1, 1], [3, 2], [4, 1], [5]] +@test integer_partitions(0) == [[]] +@test integer_partitions(5) == reverse(Any[[1, 1, 1, 1, 1], [2, 1, 1, 1], [2, 2, 1], [3, 1, 1], [3, 2], [4, 1], [5]]) @test_throws DomainError integer_partitions(-1) @test_throws ArgumentError prevprod([2,3,5],Int128(typemax(Int))+1)