feat: add limited round-robin scheduling

This commit is contained in:
dahyeon committed 2026-06-19 01:13:50 -07:00
1 parent 24983aeb09
commit 658592973e
15 files changed
+403 -63

No files matched your search

@@ -3,11 +3,23 @@ export interface RoundRobinPair {
teamBIndex: number;
}
export interface RoundRobinGameAssignment extends RoundRobinPair {
gameNumber: number;
roundNumber: number;
}
export interface RoundRobinTeamCountInput {
teams?: Array<{ teamIndex: number }>;
participants: Array<{ excluded?: boolean }>;
}
export interface RoundRobinGameScheduleOptions {
gamesPerPair?: number;
maxRounds?: number;
rng?: () => number;
shuffleTeams?: boolean;
}
export function roundRobinPairs(teamCount: number): RoundRobinPair[] {
const pairs: RoundRobinPair[] = [];
for (let teamAIndex = 1; teamAIndex <= teamCount; teamAIndex += 1) {
@@ -27,6 +39,70 @@ export function roundRobinPairCount(teamCount: number): number {
return (teamCount * (teamCount - 1)) / 2;
}
export function roundRobinRoundCount(teamCount: number): number {
if (teamCount < 2) return 0;
return teamCount % 2 === 0 ? teamCount - 1 : teamCount;
}
export function roundRobinGameSchedule(
teamCount: number,
options: RoundRobinGameScheduleOptions = {},
): RoundRobinGameAssignment[] {
if (teamCount < 2) return [];
const rawGamesPerPair = options.gamesPerPair ?? 1;
const gamesPerPair = Number.isFinite(rawGamesPerPair)
? Math.max(1, Math.floor(rawGamesPerPair))
: 1;
const fullRoundCount = roundRobinRoundCount(teamCount);
const requestedRoundCount =
typeof options.maxRounds === 'number' && Number.isFinite(options.maxRounds)
? Math.floor(options.maxRounds)
: fullRoundCount;
const roundLimit = Math.max(
0,
Math.min(fullRoundCount, requestedRoundCount),
);
if (roundLimit === 0) return [];
const bye = 0;
const teams = Array.from({ length: teamCount }, (_, index) => index + 1);
if (options.shuffleTeams) shuffleInPlace(teams, options.rng);
if (teams.length % 2 === 1) teams.push(bye);
const rotating = [...teams];
const schedule: RoundRobinGameAssignment[] = [];
let gameNumber = 1;
for (let roundIndex = 0; roundIndex < roundLimit; roundIndex += 1) {
const roundNumber = roundIndex + 1;
for (let index = 0; index < rotating.length / 2; index += 1) {
const left = rotating[index];
const right = rotating[rotating.length - 1 - index];
if (left === bye || right === bye) continue;
const teamAIndex = Math.min(left, right);
const teamBIndex = Math.max(left, right);
for (let gameIndex = 0; gameIndex < gamesPerPair; gameIndex += 1) {
schedule.push({
gameNumber,
roundNumber,
teamAIndex,
teamBIndex,
});
gameNumber += 1;
}
}
const fixed = rotating[0];
const tail = rotating.slice(1);
tail.unshift(tail.pop() as number);
rotating.splice(0, rotating.length, fixed, ...tail);
}
return schedule;
}
export function resolveRoundRobinTeamCount(
match: RoundRobinTeamCountInput,
): number {