nextpart: Next partition

nextpartR Documentation

Next partition


Given a partition, return the “next” one; or determine whether it is the last one.


  nextpart(part, check=TRUE)
  nextdiffpart(part, check=TRUE)
  nextrestrictedpart(part, check=TRUE)
 firstrestrictedpart(n, m,
  nextblockpart(part, f, n=sum(part), include.fewer=FALSE, check=TRUE)
islastblockpart(part, f, n=NULL     , include.fewer=FALSE)
 firstblockpart(      f, n=NULL     , include.fewer=FALSE)
  nextcomposition(comp, restricted,, check=TRUE)
islastcomposition(comp, restricted,
 firstcomposition(n,    m=NULL    ,



A partition or composition


Boolean, with default TRUE meaning to carry out various safety checks; the next() functions use C calls which might crash the session with some inputs

f, n, include.fewer, m,

Other arguments as per the vectorized version


In function nextcomposition() and islastcomposition(), Boolean, with TRUE meaning to consider compositions of fixed length [eg, to iterate through the columns of compositions(6,3)], and FALSE meaning to consider compositions of any length [eg to iterate through the columns of compositions(6)]


These functions are intended to enumerate partitions one at a time, eliminating the need to store a huge matrix. This is useful for optimization over large domains and makes it possible to investigate larger partitions than is possible with the vectorized codes.

The idea is to use a first...() function to generate the first partition, then iterate using a next...() function, stopping when the islast...() function returns TRUE.

An example is given below, in which the “scrabble” problem is solved; note the small size of the sample space. More examples are given in the tests/aab.R file.


Functions nextpart() and nextdiffpart() require a vector of the right length: they require and return a partition padded with zeros. Functions nextrestrictedpart() and nextblockpart() work with partitions of the specified length. Function nextcomposition() truncates any zeros at the end of the composition. This behaviour is inherited from the C code.

In functions nextcomposition() and firstcomposition(), argument is ignored if restricted is FALSE.

I must say that the performance of these functions is terrible; they are much much slower than their vectorized equivalents. The magnitude of the difference is much larger than I expected. Heigh ho. Frankly you would better off working directly in C.


Robin K. S. Hankin

See Also



# Do the optimization in scrabble vignette, one partition at a time:
# (but with a smaller letter bag)
scrabble <- c(a=9 , b=2 , c=2 , d=4 , e=12 , f=2 , g=3)

f <- function(a){prod(choose(scrabble,a))/choose(sum(scrabble),7)}
bestsofar <- 0
a <- firstblockpart(scrabble,7)
  jj <- f(a)
    bestsofar <- jj
    bestpart <- a
  a <- nextblockpart(a,scrabble) 

RobinHankin/partitions documentation built on April 9, 2022, 12:43 p.m.