Inclusion, exclusion and pigeonholes
Two principles that carry a surprising share of combinatorics: counting a union by adding and subtracting overlaps, and the fact that too many things in too few boxes must collide. Both are here on actual data and as formulas.
On sets you can list
For sets ,
inclusionExclusion(sets) computes each level of that sum, so the answer comes with its working.
import { inclusionExclusion } from "@ratmath/discrete";
const r = inclusionExclusion([[1, 2, 3, 4], [3, 4, 5], [4, 5, 6, 7]], { universe: 10 });
r.union; // 7n
r.none; // 3n: of a universe of 10, how many are in none of the sets
r.terms; // [{ size: 1, sign: 1, sum: 11n, count: 3n },
// { size: 2, sign: -1, sum: 5n, count: 3n },
// { size: 3, sign: 1, sum: 1n, count: 1n }] 11 − 5 + 1 = 7
Sets are arrays or Sets. universe is a count, an array or a Set. Up to 20 sets are accepted, since the formula has terms; intersections that are already empty are not explored further.
By formula: the sieve
Most uses never list anything. There are "bad" properties, the number of objects with any particular of them is a known (the same for every choice, by symmetry), and the number with none is
import { sieve, factorial } from "@ratmath/discrete";
// Derangements of 5: property i is "i stays in place"; fixing k of them leaves (5 − k)! permutations.
const d = sieve(5, (k) => factorial(5 - k));
d.none; // 44n
d.all; // 120n
d.union; // 76n: permutations with at least one fixed point
d.terms.map((t) => `${t.sign > 0 ? "+" : "-"}${t.choices}·${t.each}`);
// ["+1·120", "-5·24", "+10·6", "-10·2", "+5·1", "-1·1"]
// Functions from 6 things onto 3: property i is "value i is never taken".
sieve(3, (k) => BigInt(3 - k) ** 6n).none; // 540n = 3!·S(6, 3)
The derangement sum simplifies to , which is why the proportion of derangements tends to . The second example is the formula for surjections, and dividing by gives the Stirling numbers of the second kind.
Pigeonholes
If things go into boxes, some box holds at least . pigeonhole states the bound; collision finds an actual pair in the same box, given a function that says which box a thing goes in.
import { pigeonhole, collision } from "@ratmath/discrete";
pigeonhole(13, 12); // { atLeast: 2n, atMost: 1n, forced: true, statement: "13 items in 12 boxes: some box holds at least 2" }
pigeonhole(100, 7).atLeast; // 15n
// Among any 12 whole numbers, two differ by a multiple of 11: the boxes are the remainders.
collision([3, 14, 25, 7, 18, 40, 2, 9, 61, 33, 12, 5], (x) => x % 11);
// { key: 3, items: [3, 14], indices: [0, 1] }
collision([1, 2, 3]); // null: all different
The principle only says a collision exists; it does not say where. That gap is real: it is easy to prove that two people in a large city have the same number of hairs and hard to find them. collision closes the gap for data you hold.
@ratmath/discrete and Core's Rational in scope. The last line's value is shown; PRINT(…) adds lines, TEX(…) typesets math.