js实现赛程
赛程实现的基本思路
使用JavaScript实现赛程安排需要考虑比赛轮次、对阵组合以及时间分配。常见的赛程类型包括单循环赛、双循环赛和淘汰赛,具体实现需根据实际需求调整。
单循环赛实现
单循环赛指每支队伍与其他队伍各比赛一次。以下是一个简单的实现示例:
function generateRoundRobin(teams) {
const schedule = [];
const numTeams = teams.length;
const rounds = numTeams - 1;
for (let round = 0; round < rounds; round++) {
const roundMatches = [];
for (let i = 0; i < numTeams / 2; i++) {
const home = teams[i];
const away = teams[numTeams - 1 - i];
if (home && away) {
roundMatches.push({ home, away, round });
}
}
schedule.push(roundMatches);
teams.splice(1, 0, teams.pop());
}
return schedule.flat();
}
双循环赛实现
双循环赛是在单循环基础上增加主客场互换:
function generateDoubleRoundRobin(teams) {
const firstHalf = generateRoundRobin(teams);
const secondHalf = firstHalf.map(match => ({
home: match.away,
away: match.home,
round: match.round + teams.length - 1
}));
return [...firstHalf, ...secondHalf];
}
淘汰赛实现
淘汰赛适合需要快速决出冠军的场景:
function generateKnockout(teams) {
const matches = [];
let currentRound = [...teams];
let roundNumber = 0;
while (currentRound.length > 1) {
const nextRound = [];
for (let i = 0; i < currentRound.length; i += 2) {
const match = {
home: currentRound[i],
away: currentRound[i + 1],
round: roundNumber
};
matches.push(match);
nextRound.push(`Winner of ${i}-${i+1}`);
}
currentRound = nextRound;
roundNumber++;
}
return matches;
}
时间安排优化
为赛程添加时间属性可提高实用性:
function addScheduleDates(matches, startDate, daysBetweenRounds) {
const date = new Date(startDate);
let currentRound = -1;
return matches.map(match => {
if (match.round !== currentRound) {
date.setDate(date.getDate() + daysBetweenRounds);
currentRound = match.round;
}
return {
...match,
date: new Date(date)
};
});
}
可视化输出
将生成的赛程渲染为HTML表格:
function renderSchedule(schedule) {
const table = document.createElement('table');
const header = table.createTHead();
const headerRow = header.insertRow();
['Round', 'Date', 'Home', 'Away'].forEach(text => {
const th = document.createElement('th');
th.textContent = text;
headerRow.appendChild(th);
});
const body = table.createTBody();
schedule.forEach(match => {
const row = body.insertRow();
[match.round, match.date.toDateString(), match.home, match.away].forEach(text => {
const cell = row.insertCell();
cell.textContent = text;
});
});
document.body.appendChild(table);
}
实际应用建议
- 对于大型赛事应考虑使用专业算法库如
round-robin-tournament - 添加异常处理确保队伍数量为偶数时自动处理轮空情况
- 考虑实现持久化存储将赛程保存至数据库
- 前端框架用户可结合React/Vue实现动态交互式赛程表
以上实现可根据具体需求进行调整扩展,如添加比分记录、积分计算等功能。







