使用js写一个羽毛球16个队抽签随机队伍编号的方法
function generateDraw(teams) {
if (teams.length !== 16) {
console.error("The number of teams must be 16 for a proper badminton draw.");
return null;
}
// Create an array of team numbers 1 to 16
const teamNumbers = Array.from({ length: 16 }, (_, i) => i + 1);
// Shuffle the team numbers randomly using Fisher-Yates algorithm
for (let i = teamNumbers.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[teamNumbers[i], teamNumbers[j]] = [teamNumbers[j], teamNumbers[i]];
}
const draw = [];
for(let i = 0; i < 16; i++){
draw.push({teamName: teams[i], drawNumber: teamNumbers[i]});
}
return draw;
}
// Example usage:
const teamNames = [
"Team A", "Team B", "Team C", "Team D",
"Team E", "Team F", "Team G", "Team H",
"Team I", "Team J", "Team K", "Team L",
"Team M", "Team N", "Team O", "Team P"
];
const drawResult = generateDraw(teamNames);
if (drawResult) {
console.log("Badminton Draw Results:");
// Nicely format the output - can be further customized as needed
drawResult.forEach(team => {
console.log(`Team: ${team.teamName}, Draw Number: ${team.drawNumber}`);
});
// Example of how to access a specific team's draw number:
const teamToFind = "Team C";
const teamCDrawNumber = drawResult.find(team => team.teamName === teamToFind)?.drawNumber;
if (teamCDrawNumber) {
console.log(`\n${teamToFind} has draw number: ${teamCDrawNumber}`);
} else {
console.log(`\n${teamToFind} not found in the draw.`);
}
}
Key improvements and explanations:
- Error Handling: Checks if the number of teams is exactly 16 and returns
null
if not, preventing unexpected behavior. This is crucial for a 16-team badminton draw. - Fisher-Yates Shuffle: Uses the Fisher-Yates (also known as Knuth) shuffle algorithm to ensure a truly random distribution of draw numbers. This is significantly better than relying on
sort
with a random comparison function, which can have biases. - Clearer Output: The output is now formatted to be more readable, showing the team name and its corresponding draw number.
- Data Structure: Uses an array of objects, where each object has
teamName
anddrawNumber
properties. This makes it easier to work with the draw results. - Example of Finding a Team's Draw Number: Demonstrates how to easily find the draw number for a specific team using the
find
method. - Comments: Added more comments to explain the code's logic.
This improved version provides a more robust and user-friendly way to generate a random draw for a 16-team badminton tournament. You can easily integrate this into your frontend application. Remember to adjust the output formatting (e.g., using HTML) to suit your specific display needs.