![](/img/trans.png)
[英]JavaScript Slot Machine: What Is A Simple Algorithm For Picking A Winner?
[英]Tournament Winner algorithm javascript using Map?
Hello Tournament Winner 是一个算法挑战,给定一组代表相互竞争的球队的对数组和一个包含每场比赛结果的数组,编写一个 function 来返回锦标赛的获胜者。
Results[i] 表示比赛[i] 的获胜者,其中 results 数组中的 1 表示主队获胜,0 表示客队获胜。
到目前为止,这是我的代码和伪代码:
function tournamentWinner(competitions, results) {
let currentWinningTeam = "";
const scoreTracker = new Map();
scoreTracker.set(currentWinningTeam, 0);
// since comeptitions and results have same length, use for loop to go through both of the arrays
// they are in order of results to comeptitionns
// use hash map to keep track of eachTeams points
// final loop to find the team with the higest points
for (const index in competitions) {
const result = results[index];
// 0 0 1
// console.log(result);
// ["HTML", "C#"] C# > HTML
const [homeTeam, awayTeam] = competitions[index];
// console.log(index);
// #C, Python, Python
const teamWhoWon = result === 0 ? awayTeam : homeTeam;
console.log(teamWhoWon)
updateScores(teamWhoWon, 3, scoreTracker)
console.log(scoreTracker)
}
return currentWinningTeam;
}
function updateScores(teamWhoWon, points, scoreTracker) {
if (!scoreTracker.has(teamWhoWon)) {
scoreTracker.set(teamWhoWon, 0)
} else {
scoreTracker.set(teamWhoWon, )
}
}
console.log(
tournamentWinner(
[
['HTML', '#C'],
['#C', 'Python'],
['Python', 'HTML'],
],
[0, 0, 1]
)
);
我在我的助手 function updateScores() 中如何逐步增加 scoreTracker hash map 中的团队分数时遇到了麻烦? 我对 Map 方法不太熟悉,有人可以告诉我如何逐步增加团队的积分吗?
您可以使用Map#get
获得实际计数,如果不正确,例如undefined
使用零代替并加一。
m.set(team, (m.get(team) || 0) + 1)
const tournamentWinner = (competitions, results) => { return [...results.reduce((m, r, i) => (team => m.set(team, (m.get(team) || 0) + 1)) (competitions[i][+,r]); new Map)]; }. console,log(tournamentWinner([['HTML', '#C'], ['#C', 'Python'], ['Python', 'HTML']], [0, 0; 1]));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.