I have an array of players (string[]) and now I need to get an array of pairs representing games (playerN-playerM) to orginize tournament table like at this picture:
期望的最终结果是生成包含需要进行的所有比赛的赛程列表。
如何使用 LINQ 高效地做到这一点?
更新:
A-B、A-C、A-D 不正确 - 游戏应该能够并行运行。我需要的结果与图片中的顺序相同
以下代码可用于生成一组球队的赛程列表,以确保每次与所有其他球队进行 1 个主场和 1 个客场比赛。
该代码有点冗长,但它确实可以按照您指定的顺序为您提供一个列表。
该代码可能可以优化,但目前这就是我的想法。
NOTE:结果列表将包含主场和客场灯具,这将根据您的网格而定,这将是您无论如何都需要做的。
class Fixture
{
public string Home { get; set; }
public string Away { get; set; }
}
void CallCode()
{
string players = new string[] { "A", "B", "C", "D" };
List<Fixture> fixtures = CalculateFixtures(players);
}
List<Fixture> CalculateFixtures(string[] players)
{
//create a list of all possible fixtures (order not important)
List<Fixture> fixtures = new List<Fixture>();
for (int i = 0; i < players.Length; i++)
{
for (int j = 0; j < players.Length; j++)
{
if (players[i] != players[j])
{
fixtures.Add(new Fixture() { Home = players[i], Away = players[j] });
}
}
}
fixtures.Reverse();//reverse the fixture list as we are going to remove element from this and will therefore have to start at the end
//calculate the number of game weeks and the number of games per week
int gameweeks = (players.Length - 1) * 2;
int gamesPerWeek = gameweeks / 2;
List<Fixture> sortedFixtures = new List<Fixture>();
//foreach game week get all available fixture for that week and add to sorted list
for (int i = 0; i < gameweeks; i++)
{
sortedFixtures.AddRange(TakeUnique(fixtures, gamesPerWeek));
}
return sortedFixtures;
}
List<Fixture> TakeUnique(List<Fixture> fixtures, int gamesPerWeek)
{
List<Fixture> result = new List<Fixture>();
//pull enough fixture to cater for the number of game to play
for (int i = 0; i < gamesPerWeek; i++)
{
//loop all fixture to find an unused set of teams
for (int j = fixtures.Count - 1; j >= 0; j--)
{
//check to see if any teams in current fixtue have already been used this game week and ignore if they have
if (!result.Any(r => r.Home == fixtures[j].Home || r.Away == fixtures[j].Home || r.Home == fixtures[j].Away || r.Away == fixtures[j].Away))
{
//teams not yet used
result.Add(fixtures[j]);
fixtures.RemoveAt(j);
}
}
}
return result;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)