当前位置:首页 > JavaScript

js实现赛程

2026-01-31 16:09:59JavaScript

赛程生成的基本思路

赛程生成通常涉及循环赛或淘汰赛的编排,需要合理安排比赛顺序避免冲突。循环赛确保每支队伍与其他队伍至少交锋一次,淘汰赛则逐步淘汰队伍直至决出冠军。

循环赛算法实现

使用双循环法可以生成主客场赛程。将队伍列表分为两部分,通过旋转数组模拟对战组合。

js实现赛程

function generateRoundRobin(teams) {
  const schedule = [];
  const numTeams = teams.length;
  const half = Math.floor(numTeams / 2);

  for (let round = 0; round < numTeams - 1; round++) {
    const roundMatches = [];
    for (let i = 0; i < half; i++) {
      const home = teams[i];
      const away = teams[numTeams - 1 - i];
      if (home && away) {
        roundMatches.push({ home, away });
      }
    }
    schedule.push(roundMatches);

    // 旋转数组(保留第一个元素)
    teams.splice(1, 0, teams.pop());
  }
  return schedule;
}

淘汰赛算法实现

淘汰赛需要处理队伍数量不是2的幂次方的情况,通过首轮轮空实现平衡。

js实现赛程

function generateKnockout(teams) {
  const rounds = [];
  let currentRound = [...teams];

  while (currentRound.length > 1) {
    const nextRound = [];
    const matches = [];

    for (let i = 0; i < currentRound.length; i += 2) {
      if (i + 1 < currentRound.length) {
        matches.push({
          team1: currentRound[i],
          team2: currentRound[i + 1]
        });
        nextRound.push(null); // 胜者待定
      } else {
        nextRound.push(currentRound[i]); // 轮空
      }
    }

    rounds.push(matches);
    currentRound = nextRound;
  }
  return rounds;
}

可视化赛程输出

将生成的赛程格式化为可读性更高的表格形式。

function printSchedule(schedule) {
  schedule.forEach((round, index) => {
    console.log(`Round ${index + 1}:`);
    round.forEach(match => {
      console.log(`  ${match.home} vs ${match.away}`);
    });
  });
}

处理奇数队伍情况

当队伍数量为奇数时,自动添加轮空位保持算法稳定性。

function prepareTeams(rawTeams) {
  const teams = [...rawTeams];
  if (teams.length % 2 !== 0) {
    teams.push(null); // 轮空标记
  }
  return teams;
}

完整调用示例

const teams = ['Team A', 'Team B', 'Team C', 'Team D'];
const preparedTeams = prepareTeams(teams);

const roundRobin = generateRoundRobin(preparedTeams);
printSchedule(roundRobin);

const knockout = generateKnockout(teams);
console.log(knockout);

标签: 赛程js
分享给朋友:

相关文章

js实现继承

js实现继承

原型链继承 通过将子类的原型指向父类的实例实现继承。子类实例可以访问父类原型上的属性和方法。 function Parent() { this.name = 'parent'; } Parent…

js实现图片

js实现图片

图片加载与显示 在JavaScript中,可以通过Image对象动态加载图片。创建实例后设置src属性触发加载,通过onload回调处理加载完成后的操作: const img = new Ima…

js 实现跳转

js 实现跳转

使用 window.location.href 进行跳转 通过修改 window.location.href 可以跳转到指定 URL,浏览器会加载新页面: window.location.hre…

js实现滑动

js实现滑动

实现滑动效果的方法 在JavaScript中实现滑动效果可以通过多种方式完成,以下是几种常见的实现方法: 使用CSS过渡和JavaScript触发 通过CSS定义过渡效果,JavaScript控制触…

js 实现全屏

js 实现全屏

使用 requestFullscreen 方法 通过调用元素的 requestFullscreen 方法可以实现全屏。该方法兼容现代浏览器,但不同浏览器可能需要前缀。 const element =…

js实现左右滑动

js实现左右滑动

实现左右滑动的 JavaScript 方法 监听触摸事件 通过 touchstart、touchmove 和 touchend 事件来检测用户的手势操作。记录触摸的起始位置和移动距离,判断滑动方向。…