Enumeration

Enumeration with ranking

Listing every object of a kind is the oldest method in combinatorics and the first to run out of time. A ranked list does better: it knows what stands at each place without writing the others down.

A family

Each function below returns a Family: a finite list of objects in a fixed, documented order.

import { permutations } from "@ratmath/discrete";

const p = permutations(4);
p.count;                  // 24n
p.unrank(0);              // [1, 2, 3, 4]
p.unrank(23);             // [4, 3, 2, 1]      (unrank(-1) is the last, too)
p.rank([2, 1, 4, 3]);     // 7n
p.has([1, 1, 2, 3]);      // false
p.first(3);               // [[1,2,3,4], [1,2,4,3], [1,3,2,4]]
[...p].length;            // 24: a family is iterable
p.random(rng(7));         // a uniformly random one

Given a number nn, the things arranged are 1,…,n1, \dots, n. Given an array, they are its items: permutations(["a", "b", "c"]). Ranks are BigInts counted from 0.

The families

FamilyObjectsCountOrder
permutations(n)arrangements of all nnn!n!lexicographic
permutations(n, k)arrangements of kk out of nnn!/(n−k)!n!/(n-k)!lexicographic
derangements(n)permutations with no fixed pointDnD_nlexicographic
combinations(n, k)kk-subsets, each increasing(nk)\binom nklexicographic
multisets(n, k)kk from nn with repeats, non-decreasing(n+k−1k)\binom{n+k-1}{k}lexicographic
subsets(n)all subsets2n2^nbinary; or { order: "gray" }, "size"
words(n, k)kk-letter words, repeats allowednkn^kdictionary
product(a, b, …)one from each array or familyproductlast varies fastest
compositions(n), (n, k)ordered sums of positive parts2n−12^{n-1}, (n−1k−1)\binom{n-1}{k-1}lexicographic
compositions(n, k, { zero: true })nn identical things in kk boxes(n+k−1k−1)\binom{n+k-1}{k-1}lexicographic
partitions(n), (n, k)unordered sums, largest part firstp(n)p(n), p(n,k)p(n, k)largest first part first
setPartitions(n), (n, k)splits of a set into blocksBnB_n, S(n,k)S(n, k)restricted growth
dyckWords(n)balanced strings of nn pairs of bracketsCatalan( before )

How ranking works

One idea does all of them: count the completions of a prefix. To find the permutation of 4 at place 7, ask how many permutations start with 1: 3!=63! = 6. Place 7 is past those, so the first entry is 2 and we want place 7−6=17 - 6 = 1 among the permutations starting with 2. Each next entry accounts for 2!=22! = 2: place 1 is within the first block, so the next entry is the smallest unused, 1. Then 1!1! each: place 1 skips one, so 4, then 3. The answer is [2,1,4,3][2, 1, 4, 3], found with a handful of divisions, and the same walk run backwards is rank.

All that changes from family to family is the count of completions:

  • combinations: after choosing the element vv, (n−vleft to choose)\binom{n-v}{\text{left to choose}};
  • integer partitions: the number of partitions of what is left with parts no larger than the last one;
  • set partitions: element ii joins one of the mm open blocks or opens a new one, and the number of ways to finish satisfies w(r,m)=m w(r−1,m)+w(r−1,m+1)w(r, m) = m\,w(r-1, m) + w(r-1, m+1);
  • bracket strings: the ballot numbers, the number of ways to finish from a given height;
  • derangements: an inclusion and exclusion sum that depends only on how many of the remaining places could still be fixed points.
import { partitions, setPartitions, dyckWords, derangements } from "@ratmath/discrete";

partitions(4).toArray();        // [[4], [3,1], [2,2], [2,1,1], [1,1,1,1]]
setPartitions(3).toArray();     // [[[1,2,3]], [[1,2],[3]], [[1,3],[2]], [[1],[2,3]], [[1],[2],[3]]]
dyckWords(3).toArray();         // ["((()))", "(()())", "(())()", "()(())", "()()()"]
derangements(3).toArray();      // [[2,3,1], [3,1,2]]

const big = setPartitions(30);
big.count;                      // 846749014511809332450147n
big.unrank(10n ** 20n);         // found at once

What it is good for

Uniform random objects. family.random(rng) draws a uniform place and unranks it, so every object is exactly equally likely. For partitions and set partitions that is not easy to get any other way: "put each element in a random block" does not give uniform set partitions.

Splitting a search. Ten workers can each take a tenth of the places, with nothing shared but two numbers. A search that was interrupted resumes from the rank where it stopped.

Compact names. A rank is the shortest possible name for an object: a 5-card hand is a number below 2,598,960, which is 22 bits.

Gray codes. subsets(n, { order: "gray" }) lists subsets so that neighbours differ in exactly one element, which is the order to use when each step updates a running total.

Try itEdit the code and run it with @ratmath/discrete and Core's Rational in scope. The last line's value is shown; PRINT(…) adds lines, TEX(…) typesets math.
Ctrl/⌘ + Enter runs