// The draw: a random assignment giver -> receiver where nobody draws themselves and no excluded pair is // used (a derangement with exclusions). Runs entirely on the organiser's device. // // Strategy, in order: // 1. Feasibility: a maximum bipartite matching (givers x receivers over the allowed pairs). If it is not // perfect, the draw is impossible and Hall's theorem gives a set of givers that can only draw among // fewer receivers than they are: that set is named in the error, so the organiser knows what to free. // 2. "Corrente Ășnica" (optional): one single cycle through everyone, found by randomised backtracking with a // step budget. If none is found the draw falls back to step 3 and says so (singleCycle: false). // 3. Rejection sampling: shuffle until the permutation respects every rule (uniform over valid draws); // after many failures (tight exclusions), randomised backtracking, then the matching from step 1, // which is always valid. So a feasible draw never fails. import { makeRng, randInt, randomSeed, shuffle, type Rng } from './random'; export interface DrawInput { /** Participant count. Names are not needed by the algorithm. */ n: number; /** Pairs [a, b] that must not draw each other (both directions), e.g. couples. */ pairs?: [number, number][]; /** Directed exclusions [giver, receiver]: giver must not draw receiver. */ oneWay?: [number, number][]; /** Try to make one single cycle (the reveal at the party goes person to person without breaking). */ singleCycle?: boolean; /** Fixed seed for reproducible draws (tests). Omit in production. */ seed?: string; } export type DrawError = | { kind: 'too-few'; n: number } | { kind: 'no-option'; giver: number } | { kind: 'no-giver'; receiver: number } | { kind: 'hall'; givers: number[]; receivers: number[] }; export type DrawResult = | { ok: true; to: number[]; singleCycle: boolean; seed: string } | { ok: false; error: DrawError }; export const MIN_PEOPLE = 3; /** allowed[g][r]: may giver g draw receiver r? */ export function allowedMatrix(input: DrawInput): boolean[][] { const { n } = input; const m = Array.from({ length: n }, (_, g) => Array.from({ length: n }, (_, r) => g !== r)); for (const [a, b] of input.pairs ?? []) { if (a >= 0 && b >= 0 && a < n && b < n) { m[a][b] = false; m[b][a] = false; } } for (const [g, r] of input.oneWay ?? []) { if (g >= 0 && r >= 0 && g < n && r < n) m[g][r] = false; } return m; } /** Kuhn's augmenting-path matching. Returns matchG[g] = receiver or -1. Order randomised by rng. */ function maxMatching(allowed: boolean[][], rng: Rng): { matchG: number[]; matchR: number[] } { const n = allowed.length; const matchG = new Array(n).fill(-1); const matchR = new Array(n).fill(-1); const order = shuffle(rng, [...Array(n).keys()]); const cand = allowed.map((row) => shuffle(rng, row.flatMap((ok, r) => (ok ? [r] : [])))); const tryG = (g: number, seen: boolean[]): boolean => { for (const r of cand[g]) { if (seen[r]) continue; seen[r] = true; if (matchR[r] === -1 || tryG(matchR[r], seen)) { matchG[g] = r; matchR[r] = g; return true; } } return false; }; for (const g of order) tryG(g, new Array(n).fill(false)); return { matchG, matchR }; } /** Givers reachable by alternating paths from an unmatched giver: a Hall violator (|N(S)| < |S|). */ function hallViolator(allowed: boolean[][], matchG: number[], matchR: number[]): { givers: number[]; receivers: number[] } { const n = allowed.length; const start = matchG.indexOf(-1); const S = new Set([start]); const T = new Set(); const queue = [start]; while (queue.length) { const g = queue.shift()!; for (let r = 0; r < n; r++) { if (!allowed[g][r] || T.has(r)) continue; T.add(r); const g2 = matchR[r]; if (g2 !== -1 && !S.has(g2)) { S.add(g2); queue.push(g2); } } } return { givers: [...S].sort((a, b) => a - b), receivers: [...T].sort((a, b) => a - b) }; } /** Check feasibility; returns an error explaining why the draw is impossible, or null. */ export function checkFeasible(input: DrawInput, allowed = allowedMatrix(input)): DrawError | null { const { n } = input; if (n < MIN_PEOPLE) return { kind: 'too-few', n }; for (let g = 0; g < n; g++) if (!allowed[g].some(Boolean)) return { kind: 'no-option', giver: g }; for (let r = 0; r < n; r++) if (!allowed.some((row) => row[r])) return { kind: 'no-giver', receiver: r }; const { matchG, matchR } = maxMatching(allowed, makeRng('feasibility')); if (matchG.includes(-1)) return { kind: 'hall', ...hallViolator(allowed, matchG, matchR) }; return null; } export const isValid = (to: number[], allowed: boolean[][]) => to.length === allowed.length && new Set(to).size === to.length && to.every((r, g) => r >= 0 && allowed[g][r]); export function isSingleCycle(to: number[]): boolean { let g = 0, steps = 0; do { g = to[g]; steps++; } while (g !== 0 && steps <= to.length); return steps === to.length; } /** Randomised backtracking for one Hamiltonian cycle over allowed edges, with a step budget. */ function findCycle(allowed: boolean[][], rng: Rng, budget = 200_000): number[] | null { const n = allowed.length; const start = randInt(rng, n); const path = [start]; const used = new Array(n).fill(false); used[start] = true; let steps = 0; const dfs = (g: number): boolean => { if (++steps > budget) return false; if (path.length === n) return allowed[g][start]; // fewest onward options first (Warnsdorff), ties broken randomly const next = shuffle(rng, allowed[g].flatMap((ok, r) => (ok && !used[r] ? [r] : []))) .map((r) => ({ r, deg: allowed[r].reduce((c, ok, x) => c + (ok && !used[x] ? 1 : 0), 0) })) .sort((a, b) => a.deg - b.deg); for (const { r } of next) { used[r] = true; path.push(r); if (dfs(r)) return true; used[r] = false; path.pop(); if (steps > budget) return false; } return false; }; if (!dfs(start)) return null; const to = new Array(n); for (let i = 0; i < n; i++) to[path[i]] = path[(i + 1) % n]; return to; } /** Randomised backtracking over givers, most constrained first. */ function backtrack(allowed: boolean[][], rng: Rng, budget = 200_000): number[] | null { const n = allowed.length; const order = shuffle(rng, [...Array(n).keys()]).sort( (a, b) => allowed[a].filter(Boolean).length - allowed[b].filter(Boolean).length, ); const to = new Array(n).fill(-1); const taken = new Array(n).fill(false); let steps = 0; const go = (i: number): boolean => { if (i === n) return true; if (++steps > budget) return false; const g = order[i]; for (const r of shuffle(rng, allowed[g].flatMap((ok, r) => (ok && !taken[r] ? [r] : [])))) { to[g] = r; taken[r] = true; if (go(i + 1)) return true; taken[r] = false; to[g] = -1; } return false; }; return go(0) ? to : null; } export function draw(input: DrawInput): DrawResult { const seed = input.seed ?? randomSeed(); const rng = makeRng(seed); const allowed = allowedMatrix(input); const err = checkFeasible(input, allowed); if (err) return { ok: false, error: err }; const n = input.n; if (input.singleCycle) { const cyc = findCycle(allowed, rng); if (cyc) return { ok: true, to: cyc, singleCycle: true, seed }; } const perm = [...Array(n).keys()]; for (let tries = 0; tries < 5000; tries++) { shuffle(rng, perm); if (perm.every((r, g) => allowed[g][r])) return { ok: true, to: [...perm], singleCycle: isSingleCycle(perm), seed }; } const bt = backtrack(allowed, rng); if (bt) return { ok: true, to: bt, singleCycle: isSingleCycle(bt), seed }; const { matchG } = maxMatching(allowed, rng); // feasible, so this is perfect return { ok: true, to: matchG, singleCycle: isSingleCycle(matchG), seed }; }