Reference
Everything in the library
Every export of @ratmath/discrete. Whole-number arguments may be numbers, BigInts or digit strings; counts and ranks come back as BigInts. Edge weights and distances are exact Core Rationals; distances counted in edges are plain numbers.
Counting
| Export | What it does |
|---|---|
factorial(n), doubleFactorial(n) | and . |
fallingFactorial(n, k), risingFactorial(n, k) | and ; n may be negative. |
binomial(n, k) | ; 0 outside the triangle; the series coefficient for negative n. |
multinomial(k1, k2, …) | ; also takes one array. |
multichoose(n, k) | Multisets of size k from n kinds. |
pascalRow(n) | Row n of Pascal's triangle. |
stirling2(n, k), bell(n), surjections(n, k) | Set partitions into k blocks, all set partitions, functions onto a k-set. |
stirling1(n, k, { signed }) | Permutations with k cycles; signed gives the coefficients of the falling factorial. |
catalan(n), fibonacci(n), lucas(n) | Fibonacci and Lucas accept negative and very large n. |
derangementCount(n), eulerian(n, k) | Permutations with no fixed point; with exactly k descents. |
partitionCount(n), partitionCount(n, k) | Partitions of the integer n; into exactly k parts. |
compositionCount(n), compositionCount(n, k) | Ordered sums of positive parts. |
Principles
| Export | What it does |
|---|---|
inclusionExclusion(sets, { universe }) | { union, none, terms } for arrays or Sets; terms[j] has size, sign, sum, count. |
sieve(m, sizeOf) | The sieve formula for m symmetric properties: { all, none, union, terms }. |
pigeonhole(items, holes) | { atLeast, atMost, forced, statement }. |
collision(items, key) | The first two items with the same key: { key, items, indices } or null. |
Families
| Export | What it does |
|---|---|
Family | count (BigInt), unrank(i) / at(i), rank(object), has(object), random(rng or seed), first(n), slice(from, to), toArray(), iteration with for…of, name, order. |
permutations(n or items, k) | Arrangements of all, or of k, in lexicographic order. |
derangements(n or items) | Permutations with no fixed point. |
combinations(n or items, k) | k-element subsets. |
multisets(n or items, k) | Selections with repetition. |
subsets(n or items, { order }) | All subsets; order "binary", "gray" or "size". |
words(n or letters, k) | k-letter words; rank also accepts a string. |
product(a, b, …) | The Cartesian product of arrays and families. |
compositions(n, k, { zero }) | Ordered sums; with k parts; with zero parts allowed. |
partitions(n, k) | Integer partitions, largest part first. |
setPartitions(n or items, k) | Partitions of a set into blocks; exactly k blocks. |
dyckWords(n, { open, close }) | Balanced bracket strings. |
Graphs
| Export | What it does |
|---|---|
graph(spec, { multi, loops, vertices }) | An undirected graph from text "a-b b-c:3/2 d", a list of edges [[u, v, weight?]], an adjacency object, or { vertices, edges }. |
digraph(spec, options) | A directed graph; in text write a>b. |
Graph | order, size, directed, weighted, vertices(), edges() (each { id, from, to, weight }), hasVertex, hasEdge, edge, edgesBetween, weight, addVertex, addEdge, removeVertex, removeEdge, neighbors, inNeighbors, outEdges, inEdges, degree, inDegree, outDegree, degreeSequence, copy, subgraph, edgeSubgraph, complement, reverse, underlying, lineGraph, adjacencyMatrix, totalWeight, toString. |
cartesianProduct, tensorProduct, strongProduct, lexicographicProduct | Products; vertices named "a,b". |
disjointUnion, join, union | Side by side; side by side and fully joined; on shared vertex names. |
complete, emptyGraph, pathGraph, cycleGraph, star, wheel | The basic families on 1…n (star and wheel have centre 0). |
completeBipartite, completeMultipartite, turan | Complete multipartite graphs; Turán's extremal graph. |
hypercube(d), grid(m, n), circulant(n, jumps), kneser(n, k), petersen(), platonic(name) | Named families. |
completeDigraph, transitiveTournament, directedCycle | Directed families. |
randomGraph(n, p, rng, { directed }), randomGraphWithEdges(n, m, rng) | G(n, p) with exact p; G(n, m). |
toWeight(w) | A weight as a Rational; refuses non-whole JavaScript numbers. |
Searching and connectivity
| Export | What it does |
|---|---|
bfs(g, start) | { order, depth, parent }. |
dfs(g, start?) | { order, post, parent, discovered, finished }; a forest when no start is given. |
reachable, components, isConnected | Components are weak for a directed graph, largest first. |
biconnected(g), bridges, cutVertices, blocks | One depth-first pass gives all three. |
stronglyConnectedComponents, isStronglyConnected, condensation | Tarjan's method; the condensation is numbered in topological order. |
topologicalOrder(g) | { acyclic: true, order } or { acyclic: false, cycle }. |
findCycle, isAcyclic | A closed list [v₁, …, v₁] or null. |
bipartition(g), isBipartite | { bipartite: true, parts } or { bipartite: false, oddCycle }. |
distances, distance, eccentricity, diameter, radius, center, periphery | Distances counted in edges; Infinity when unreachable. |
girth(g) | { girth, cycle }: a shortest cycle. |
Paths, tours and trees
| Export | What it does |
|---|---|
shortestPath(g, s, t, { weighted }) | { distance, path, edges } or null; throws negative-cycle with .cycle. |
shortestPaths(g, s) | { distance: Map, parent, pathTo(t), method, negativeCycle }: breadth-first, Dijkstra or Bellman–Ford. |
allPairsShortestPaths(g) | Floyd–Warshall: { matrix, distance(u, v), path(u, v), negativeCycle }. |
eulerTour(g, { closed }) | { exists, closed, vertices, edges }, or the reason with the odd (or unbalanced) vertices. |
hamiltonCycle(g), hamiltonPath(g) | Exhaustive search (Held–Karp), up to 20 vertices; quick reasons first. |
isTree, isForest | |
minimumSpanningTree(g, { method, maximum }) | Kruskal or Prim: { weight, edges, tree, connected }. |
spanningTreeCount(g), determinant(rows) | The matrix-tree theorem, by exact Bareiss elimination. |
prufer(tree), fromPrufer(code, vertices) | Prüfer codes, both ways. |
labelledTrees(n or labels), randomTree(n, rng) | The nn−2 labelled trees as a Family; a uniform one. |
Linear programming and games
| Export | What it does |
|---|---|
linearProgram({ maximize | minimize, constraints, names, free }) | Exact two-phase simplex (Bland's rule). Coefficients as arrays or objects keyed by name; constraints [coefficients, "<=" | ">=" | "=", rhs, name?]. Returns an LPResult. |
LPResult | status ("optimal", "infeasible", "unbounded"), value, x, solution, dual, prices, binding, farkas, ray, pivots, check(). |
checkLinearProgram(problem, result), isFeasible(problem, x) | Check a certificate by arithmetic on the constraints alone; throws certificate-fails with the reason. |
integerProgram(problem, { integer, binary, maxNodes }) | Branch and bound: { status, value, x, solution, nodes, relaxation, check() }. binary: true or a list makes variables 0 or 1. |
transportation(supply, demand, cost) | The transportation problem as an exact LP: { status, plan, cost, dummy, leftover, unmet, lp }; unbalanced totals get a dummy sink or source with cost 0. |
parseProblem(spec), Problem, solveSquare(M, b) | The normalised problem (prints itself); an exact square solve. |
matrixGame(A, { rows, columns }) | Zero-sum game: value, row, column, fair, guarantee(p), cap(q), check(). |
saddlePoints(A) | Pure saddle points { row, column, value }. |
bimatrixGame(A, B?, { rows, columns }) | A BimatrixGame: payoffs(p, q), isEquilibrium(p, q), pureEquilibria(), dominance({ pureOnly }), equilibria() (with complete), lemkeHowson(label). Each equilibrium has row, column, payoffs, pure, check(). |
Generating functions and recurrences
| Export | What it does |
|---|---|
series(input), egf(seq), PowerSeries | Lazy exact power series from a list, constant or rule: coefficient(n), terms(n, { egf }), add, subtract, negate, scale, multiply, shift, reciprocal, divide, derivative, integral, compose, pow, exp, log, sqrt, toString(n). |
knownSeries | geometric(r), exp(), logInverse(), binomial(a), catalan(), partitions(). |
rationalSeries(P, Q), RationalSeries | P(x)/Q(x): series, terms, add, multiply, recurrence(). seriesPoly holds the polynomial helpers. |
recurrence({ coefficients, initial, plus }), LinearRecurrence | terms(n), term(n) (companion-matrix power), characteristic(), generatingFunction(), closedForm() → { parts, validFrom, checked, at(n), toString() } with exact algebraic roots. |
guessRecurrence(terms) | Berlekamp–Massey over Q: the shortest recurrence, or null. |
closedSum(p, r) | Σk≤n p(k)·rk in closed form: { polynomial, at(n), toString() }. |
masterTheorem({ a, b, d, j }), divideAndConquer({ a, b, f, t1 }, count) | The case, bound and reason; exact values of T(bm). |
Graph theory
| Export | What it does |
|---|---|
maximumMatching(g), checkMatching(g, edges, U) | Edmonds' blossoms: { size, edges, perfect, unmatched, certificate: { set, oddComponents, bound }, check() }, a Tutte–Berge set. |
bipartiteMatching(g, { left }) | { size, edges, perfect, cover, hall }: a König cover and a Hall violator. |
assignment(costs, { maximize }) | { assignment, cost, rowPrices, columnPrices, check() }. |
stableMatching(proposers, receivers), blockingPairs(…, matching) | Gale–Shapley: { matching, proposals, blockingPairs }. |
maxFlow(g, s, t), checkFlow(g, s, t, flow, cut) | Edmonds–Karp with exact capacities: { value, flow, cut: { source, sink, edges, capacity }, augmentations, check() }. |
chromaticNumber(g) | { number, colouring, lowerBound }; the lower bound is a clique, an odd cycle, or a complete search. |
chromaticPolynomial(g) | Deletion–contraction: { coefficients, at(k), toString() }. |
greedyColouring(g, order), isProperColouring(g, c) | A colouring as a Map; { ok, clash }. |
maximumClique, maximalCliques, maximumIndependentSet | Branch and bound; Bron–Kerbosch. |
planarity(g), isPlanar(g), checkKuratowski(g, w) | { planar: true, faces } (per block, Euler-checked) or { planar: false, kuratowski: { kind, branch, paths, edges } }. |
genus(g, { limit }), embeddingGenus(g, rotation) | { genus, proven, lower, upper, blocks: [{ rotation, faces, method }] }: the least number of handles, by rotation systems; and the genus of the surface a given rotation system draws on. See Planarity |
isomorphism(g, h), isIsomorphic(g, h) | { isomorphic: true, map } or { isomorphic: false, reason }. |
automorphisms(g) | { order, generators, orbits, group, vertices }; group is a PermGroup up to order 50,000. |
spectrum(g, { laplacian }), characteristicPolynomial(M) | Exact eigenvalues with multiplicities: { polynomial, polynomialText, eigenvalues, toString() }. |
adjacency(g), laplacian(g), walks(g, k), spanningTreesFromSpectrum(g) | BigInt matrices; Ak and its trace; τ(G) from the Laplacian polynomial. |
Combinatorial and cooperative games, voting
| Export | What it does |
|---|---|
mex, impartialGame(moves), nim(heaps), subtractionGame(S, length) | Grundy values, losing positions, winning moves; the period of a subtraction game. |
cgame(L, R), Game, starGame(n), up(), down() | Conway games in canonical form: le, ge, equals, compare, outcome, add, negate, subtract, number, nimber, L, R. |
partizanGame(position, leftMoves, rightMoves) | The canonical value of any position. |
backwardInduction(tree) | { value, plan, path }, with ties reported. |
cooperativeGame(players, v), shapley(game) | Exact Shapley values. |
core(game), inCore(game, x) | A core allocation, or a balanced collection proving the core empty; a blocking coalition. |
coreVertices(game) | Every vertex of the core: { kind: "empty" | "point" | "polytope", vertices, dimension }, up to 6 players. |
weightedVoting({ quota, weights }) | Shapley–Shubik and Banzhaf indices, swings, dummies. |
plurality, borda, instantRunoff, condorcet, approval | Winners with tallies, rounds, the pairwise table, or a Condorcet cycle. |
apportion(populations, seats, { method }) | Hamilton, Jefferson, Webster, Adams, Huntington–Hill: { seats, quotas, method, tie }. |
adjustedWinner(a, b) | Brams–Taylor for two parties. |
Relations, orders, Pólya counting
| Export | What it does |
|---|---|
relation(elements, pairs | predicate), Relation, fromPartition(blocks) | properties() with witnesses, inverse, compose, reflexive, symmetric and transitive closures, classes(). |
poset(elements, pairs | predicate), Poset | leq, hasse, minimal, maximal, least, greatest, levels, longestChain, width (Dilworth), linearExtensions, countLinearExtensions, mobius, meet, join, isLattice, isDistributive. |
divisorLattice(n), booleanLattice(n), partitionLattice(n) | The standard lattices. |
cycleIndex(G), countColourings(G, k), patternInventory(G, colours), symmetry | Burnside and Pólya; symmetry.cyclic, dihedral, symmetric, cubeFaces. |
truthTable, minterms, maxterms, countModels, fromMinterms, cnf, dnf, minimize, primeImplicants, logic | Boolean functions, re-exported from @ratmath/logic; logic is the whole package. |
Codes and designs
| Export | What it does |
|---|---|
linearCode(G, { p }), LinearCode | n, k, parityCheck, encode, messageOf, syndrome, isCodeword, codewords, weightDistribution, minimumDistance, dual, cosetLeaders, decode (with steps). |
hammingCode(r, { p }), repetitionCode, parityCode | Standard codes over Zp. |
ballSize(n, t, q), codeBounds(n, d, q), isPerfect(code) | Hamming, Singleton and Gilbert–Varshamov bounds. |
reedSolomon({ p, n, k, points }) | encode, and decode by Berlekamp–Welch with steps and error positions. |
isLatinSquare, areOrthogonal, cyclicLatinSquare(n), orthogonalLatinSquares(p) | Latin squares and complete sets of MOLS of prime order. |
blockDesign(blocks), fromDifferenceSet(D, v), projectivePlane(p), affinePlane(p), steinerTripleSystem(v) | { v, b, k, r, lambda, balanced, symmetric, checks } and the standard constructions. |
Random
| Export | What it does |
|---|---|
rng(seed) | A Random from a whole number of any size or text. |
Random | u32(), bits(k), int(n), between(lo, hi), bool(p), rational(denominator), float(), pick(items), shuffle(items), sample(items, k), weighted(items, weights), weightedIndex(weights), fork(label), clone(), state. new Random(state) resumes. |
DiscreteError | Thrown with a code: not-in-family, too-large, no-rank, bad-argument, bad-problem, certificate-fails, too-hard. |
plan | The phases still to come. |
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.