-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
41 lines (35 loc) · 1.29 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// https://en.wikipedia.org/wiki/Round-robin_tournament
function bergerTable(teams, useDummy=false, dummy={}) {
if (!Array.isArray(teams))
teams = Array.from({ length: teams }).map((_, i) => i);
else
teams = [...teams]; // copy array to avoid side effects
if (teams.length % 2 !== 0)
teams.push(dummy);
const n = teams.length;
const numberOfRounds = n-1;
const gamesPerRound = n/2;
let columnA = teams.slice(0, gamesPerRound);
let columnB = teams.slice(gamesPerRound);
const fixed = teams[0];
return Array.from({length: numberOfRounds}).map((_, i) => {
let gameCount = 1;
let round = Array.from({length: gamesPerRound}).reduce((acc, _, k) => {
if (useDummy || (columnA[k] !== dummy && columnB[k] !== dummy)) {
acc.push({
round: i+1,
game: gameCount,
teamA: columnA[k],
teamB: columnB[k]
});
gameCount++;
}
return acc;
}, []);
// rotate elements
columnA = [fixed, columnB.shift(), ...columnA.slice(1)];
columnB.push(columnA.pop());
return round;
});
}
module.exports = bergerTable;