Issue
I am able to generate the array for a knockout tournament using the below approach.
Here is a general rule for working out how many matches are in each round:
numberOfRounds = n [ [2^n-1 matches], ...., [2^0 matches] ]
So I know from this that for an 8 team tournament will have 3 rounds, and the tournament will look like this:
[ [4 matches], [2 matches], [1 match] ]
So if I pass a list of 8 teams to the tournament, the following matches array are going to be generated:
// method
function genMatches (n) {
let rounds = [];
let indices = 1;
let roundId = 0;
while (n > 1) {
roundId++;
n = (n + 1) >> 1;
var matches = [];
for (var i = 0; i < n; ++i) {
let match = {
"roundid": roundId,
"matchId": indices
};
matches.push(match);
indices++;
}
let round = {};
round['matches'] = matches;
rounds.push(round);
}
return rounds;
}
// output
[
{
"matches": [
{
"roundid": 1,
"matchId": 1
},
{
"roundid": 1,
"matchId": 2
},
{
"roundid": 1,
"matchId": 3
},
{
"roundid": 1,
"matchId": 4
}
]
},
{
"matches": [
{
"roundid": 2,
"matchId": 5
},
{
"roundid": 2,
"matchId": 6
}
]
},
{
"matches": [
{
"roundid": 3,
"matchId": 7
}
]
}
]
Now the problem is I wanted to have nextMatchId in each match object;
// expected Output
[
{
"matches": [
{
"roundid": 1,
"matchId": 1,
"nextMatchId": 5
},
{
"roundid": 1,
"matchId": 2,
"nextMatchId": 5
},
{
"roundid": 1,
"matchId": 3,
"nextMatchId": 6
},
{
"roundid": 1,
"matchId": 4,
"nextMatchId": 6
}
]
},
{
"matches": [
{
"roundid": 2,
"matchId": 5,
"nextMatchId": 7
},
{
"roundid": 2,
"matchId": 6,
"nextMatchId": 7
}
]
},
{
"matches": [
{
"roundid": 3,
"matchId": 7,
"nextMatchId": null
}
]
}
]
Any help, appreciated a lot!
Solution
Because:
- your data is always going to be a tree
- each pair of matches feeds into the match of the next round
rounds.forEach((round, roundIndex) => {
round.matches.forEach((match, matchIndex) => {
match.nextMatchId = rounds[roundIndex + 1]?.matches[Math.floor(matchIndex / 2)]?.matchId ?? null;
});
});
Which will result in your desired output:
[{
"matches": [{
"roundid": 1,
"matchId": 1,
"nextMatchId": 5
}, {
"roundid": 1,
"matchId": 2,
"nextMatchId": 5
}, {
"roundid": 1,
"matchId": 3,
"nextMatchId": 6
}, {
"roundid": 1,
"matchId": 4,
"nextMatchId": 6
}
]
}, {
"matches": [{
"roundid": 2,
"matchId": 5,
"nextMatchId": 7
}, {
"roundid": 2,
"matchId": 6,
"nextMatchId": 7
}
]
}, {
"matches": [{
"roundid": 3,
"matchId": 7,
"nextMatchId": null
}
]
}
]
Though I recommend creating it at generation time.
Answered By - Mathew Berg
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.