I try to apply the algorithm from this source to array like this:
function tournament (n) {
let pairs = [];
const k = n.length
for (let r=1; r<k; r++) {
for (let i=1; i <= k/2; i++) {
if (i==1) {
pairs.push([n[0], n[(k-1+r-1) % (k-1) + 2]]);
} else
pairs.push([n[(r+i-2) % (k-1) + 2], n[(k-1+r-i) % (k-1) + 2]]);
}
}
return pairs
}
console.log(JSON.stringify(tournament([1,2,3,4,5,6]), null, 2))
But some of pairs has null value in output. How can I fix it?
The answer is subtract 1 from each expression:
function tournament (n) {
let pairs = [];
const k = n.length
for (let r=1; r<k; r++) {
for (let i=1; i <= k/2; i++) {
if (i==1) {
pairs.push([n[1-1], n[(k-1+r-1) % (k-1) + 1]]);
} else
pairs.push([n[(r+i-2) % (k-1) + 1], n[(k-1+r-i) % (k-1) + 1]]);
}
}
return pairs
}
console.log(JSON.stringify(tournament([1,2,3,4,5,6]), null, 2))