[Math] Algorithm for generating restricted integer composition of N in k parts from interval [a,b] given the lexicographic number.

algorithmscombinatoricsdiscrete mathematics

Consider the restricted compositions of $6$ in four parts from integers $\{1, 2, 3\}$.

 1     1     1     3

 1     1     2     2

 1     1     3     1

 1     2     1     2

 1     2     2     1

 1     3     1     1

 2     1     1     2

 2     1     2     1

 2     2     1     1

 3     1     1     1

Is it possible to generate single composition entry without listing all? For example if I provide the set ($n=6$ (the number), $k=4$ the number of partitions, $a=1$, $b=3$ which means that each partition must be between $a$ and $b$, inclusively, and $i=1$, meaning we're looking for the $i$-the lexicographically smallest composition entry) and it gives $[1, 1, 1, 3]$, the $1$-th entry from the list.

Similarly,
$(n=6, k=4, a=1, b=3, i=10)$ should return $[3, 1, 1, 1]$.

I searched the literature and found two algorithms but both of them enumerate all the possibilities at once.

http://www.mathworks.com/matlabcentral/fileexchange/27110-restricted-integer-composition

http://www.mathworks.com/matlabcentral/fileexchange/44186-restricted-integer-compositions-with-fixed-number-of-parts/content/colex.m

Best Answer

Let the function $f(n, k, a, b, i)$ gives the $i$-th lexicographically smallest partition of $n$ into $k$ parts, each between $a$ and $b$, inclusively. I show how to compute $f$.

Let $g(n, k, a, b)$ be the number of partitions of $n$ into $k$ parts, each between $a$ and $b$, inclusively. Clearly $g(n, k, a, b) = \sum_{a \le j \le b} g(n-j, k-1, a, b)$.

To compute $f$, first we try all the possible first entry of the partition. For each possible entry $a \le j \le b$, we know that there are $g(n-j, k-1, a, b)$ partitions of $n$ with $j$ as its first element. Thus, we will be able to know what is the first entry of the $i$-th partition by finding the smallest $j$ such that $\sum_{a \le k \le j} g(n-j, k-1, a, b) \ge i$. The entire partition is then $j$ appended with $f(n-j, k-1, a, b, i - \sum_{a \le z \le j-1} g(n-z, k-1, a, b))$.

Related Question