基本上我有玩家名单,我想把它们配对,这样每个玩家都会玩一次。找到这些数据的最快方法是什么?
答案 0 :(得分:5)
假设玩家没有两次出现在列表中,那么双for
循环非常快:
for (int i=0, i <= playerList.Count - 2, i++)
for (int j=i+1, j <= playerList.Count - 1, j++)
//add a new pairing of player i and j
答案 1 :(得分:2)
此类锦标赛时间表通常称为round-robin。在维基百科中,还有一个可能scheduling algorithm的例子。
答案 2 :(得分:2)
我将2个实现放在一起来比较性能。非常幼稚的版本1比版本2慢大约50%。这并不是说没有更快的版本存在。
class Program
{
class Player
{
public string Name { get; set; }
public Player(string name)
{
Name = name;
}
}
class Match
{
public readonly Player Player1;
public readonly Player Player2;
public Match(Player player1, Player player2)
{
Player1 = player1;
Player2 = player2;
}
public override string ToString()
{
return string.Format("{0} vs. {1}", Player1.Name, Player2.Name);
}
}
static readonly List<Player> _players = new List<Player>()
{
new Player("John"),
new Player("Lisa"),
new Player("Matt"),
new Player("Dan"),
new Player("Steve"),
new Player("Sarah"),
new Player("Tim")
};
static void Main(string[] args)
{
const int count = 1000000;
{
var v1 = V1();
var sw = Stopwatch.StartNew();
for (int i = 0; i < count; i++)
{
v1 = V1();
}
Console.WriteLine(v1);
Console.WriteLine(sw.Elapsed);
}
{
var v2 = V2();
var sw = Stopwatch.StartNew();
for (int i = 0; i < count; i++)
{
v2 = V2();
}
Console.WriteLine(v2);
Console.WriteLine(sw.Elapsed);
}
Console.ReadLine();
}
static List<Match> V1()
{
var challengers = new List<Player>(_players);
var matches = new List<Match>();
foreach (var player in _players)
{
challengers.Remove(player);
foreach (var challenger in challengers)
{
matches.Add(new Match(player, challenger));
}
}
return matches;
}
static List<Match> V2()
{
var matches = new List<Match>();
for (int i = 0; i < _players.Count; i++)
{
for (int j = i + 1; j < _players.Count; j++)
{
matches.Add(new Match(_players[i], _players[j]));
}
}
return matches;
}
}
答案 3 :(得分:0)
一个简单的分而治之的算法:
,否则:强>
加入两个列表。
E.g。 [[(a,b)]]
和[[(c,d)]]
变为[[(a,b),(c,d)]]
。
通过轮换第二组来查找两组中的对。
E.g。 [[(a,c),(b,d)],[(a,d),(b,c)]]
(3)
+ (4)
此算法在O(n^2)
时间内运行,这是最佳的,因为它会生成(n-1)
轮n/2
个配对。
对于八名玩家,你将获得7轮:
[(a,b), (c,d), (e,f), (g,h)]
[(a,c), (b,d), (e,g), (f,h)]
[(a,d), (b,c), (e,h), (f,g)]
[(a,e), (b,f), (c,g), (e,h)]
[(a,f), (b,g), (c,h), (e,e)]
[(a,g), (b,h), (c,e), (e,f)]
[(a,h), (b,e), (c,f), (e,g)]