Files
lolympus-tournament-support/apps/api/src/modules/tournament-code/round-robin.util.ts
T
2026-05-03 02:45:52 -07:00

52 lines
1.3 KiB
TypeScript

export interface RoundRobinPair {
teamAIndex: number;
teamBIndex: number;
}
export interface RoundRobinTeamCountInput {
teams?: Array<{ teamIndex: number }>;
participants: Array<{ excluded?: boolean }>;
}
export function roundRobinPairs(teamCount: number): RoundRobinPair[] {
const pairs: RoundRobinPair[] = [];
for (let teamAIndex = 1; teamAIndex <= teamCount; teamAIndex += 1) {
for (
let teamBIndex = teamAIndex + 1;
teamBIndex <= teamCount;
teamBIndex += 1
) {
pairs.push({ teamAIndex, teamBIndex });
}
}
return pairs;
}
export function roundRobinPairCount(teamCount: number): number {
if (teamCount < 2) return 0;
return (teamCount * (teamCount - 1)) / 2;
}
export function resolveRoundRobinTeamCount(
match: RoundRobinTeamCountInput,
): number {
if (match.teams && match.teams.length > 0) {
return match.teams.length;
}
const activeParticipantCount = match.participants.filter(
(participant) => !participant.excluded,
).length;
return Math.floor(activeParticipantCount / 5);
}
export function shuffleInPlace<T>(
items: T[],
rng: () => number = Math.random,
): T[] {
for (let index = items.length - 1; index > 0; index -= 1) {
const swapIndex = Math.floor(rng() * (index + 1));
[items[index], items[swapIndex]] = [items[swapIndex], items[index]];
}
return items;
}