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

ExportWhat it does
factorial(n), doubleFactorial(n)n!n! and n!!n!!.
fallingFactorial(n, k), risingFactorial(n, k)n(n−1)⋯(n−k+1)n(n-1)\cdots(n-k+1) and n(n+1)⋯(n+k−1)n(n+1)\cdots(n+k-1); n may be negative.
binomial(n, k)(nk)\binom nk; 0 outside the triangle; the series coefficient for negative n.
multinomial(k1, k2, …)(k1+⋯+kr)!/(k1!⋯kr!)(k_1 + \dots + k_r)!/(k_1!\cdots k_r!); 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

ExportWhat 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

ExportWhat it does
Familycount (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

ExportWhat 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.
Graphorder, 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, lexicographicProductProducts; vertices named "a,b".
disjointUnion, join, unionSide by side; side by side and fully joined; on shared vertex names.
complete, emptyGraph, pathGraph, cycleGraph, star, wheelThe basic families on 1…n (star and wheel have centre 0).
completeBipartite, completeMultipartite, turanComplete 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, directedCycleDirected 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

ExportWhat 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, isConnectedComponents are weak for a directed graph, largest first.
biconnected(g), bridges, cutVertices, blocksOne depth-first pass gives all three.
stronglyConnectedComponents, isStronglyConnected, condensationTarjan's method; the condensation is numbered in topological order.
topologicalOrder(g){ acyclic: true, order } or { acyclic: false, cycle }.
findCycle, isAcyclicA closed list [v₁, …, v₁] or null.
bipartition(g), isBipartite{ bipartite: true, parts } or { bipartite: false, oddCycle }.
distances, distance, eccentricity, diameter, radius, center, peripheryDistances counted in edges; Infinity when unreachable.
girth(g){ girth, cycle }: a shortest cycle.

Paths, tours and trees

ExportWhat 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

ExportWhat 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.
LPResultstatus ("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

ExportWhat it does
series(input), egf(seq), PowerSeriesLazy 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).
knownSeriesgeometric(r), exp(), logInverse(), binomial(a), catalan(), partitions().
rationalSeries(P, Q), RationalSeriesP(x)/Q(x): series, terms, add, multiply, recurrence(). seriesPoly holds the polynomial helpers.
recurrence({ coefficients, initial, plus }), LinearRecurrenceterms(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

ExportWhat 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, maximumIndependentSetBranch 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

ExportWhat 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, approvalWinners 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

ExportWhat it does
relation(elements, pairs | predicate), Relation, fromPartition(blocks)properties() with witnesses, inverse, compose, reflexive, symmetric and transitive closures, classes().
poset(elements, pairs | predicate), Posetleq, 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), symmetryBurnside and Pólya; symmetry.cyclic, dihedral, symmetric, cubeFaces.
truthTable, minterms, maxterms, countModels, fromMinterms, cnf, dnf, minimize, primeImplicants, logicBoolean functions, re-exported from @ratmath/logic; logic is the whole package.

Codes and designs

ExportWhat it does
linearCode(G, { p }), LinearCoden, k, parityCheck, encode, messageOf, syndrome, isCodeword, codewords, weightDistribution, minimumDistance, dual, cosetLeaders, decode (with steps).
hammingCode(r, { p }), repetitionCode, parityCodeStandard 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

ExportWhat it does
rng(seed)A Random from a whole number of any size or text.
Randomu32(), 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.
DiscreteErrorThrown with a code: not-in-family, too-large, no-rank, bad-argument, bad-problem, certificate-fails, too-hard.
planThe 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.
Ctrl/⌘ + Enter runs