我正在尝试编写比赛配对算法,以避免两次玩同一位玩家
所以我们有一个玩家列表
我们先选择第一个玩家,然后再选择第一个未玩的玩家
从列表中删除
发送剩余列表以再次处理
如果最后一对不能玩,则递归应该展开,并且第一个玩家与他们尚未玩过的下一个玩家匹配,然后我们再去一次。
似乎正在发生的事情是原始列表(玩家)的大小以及通过递归调用发送的截断列表的大小都在变化。
因此,当淘汰结束时,列表播放器将减少到2个项目,而不是预期的4个或6个项目。这就像列表是通过引用而不是通过值传递的。
有什么想法吗?
编辑***
与其说列表是通过引用传递的,不如说是每次调用该过程时都会更改列表(玩家),所以我们最终通过使用a来进行该过程的第一次迭代(应该有6个玩家的列表)。递归结束时2个玩家的列表***
我把整个代码都推到了这里(以及测试列表设置代码)
using System;
using System.Collections.Generic;
using System.Runtime.ConstrainedExecution;
namespace CPair
{
class Program
{
static void Main(string[] args)
{
//create players
List<int> alist = new List<int>() { 2 };
var a = new Player(1, "a", "wk", alist, 10);
List<int> blist = new List<int>() { 1 };
var b = new Player(2, "b", "wa", blist, 9);
List<int> clist = new List<int>() { };
var c = new Player(3, "c", "bc", clist, 8);
List<int> dlist = new List<int>() { };
var d = new Player(4, "d", "wk", dlist, 7);
List<int> elist = new List<int>() { };
var e = new Player(5, "e", "bc", elist, 5);
List<int> flist = new List<int>() { };
var f = new Player(6, "f", "ab", flist, 3);
List<Player> PlayList = new List<Player>();
PlayList.Add(a);
PlayList.Add(b);
PlayList.Add(c);
PlayList.Add(d);
PlayList.Add(e);
PlayList.Add(f);
PlayList.Sort((p, q) => p.Points.CompareTo(q.Points));
foreach (Player p in PlayList)
{
Console.WriteLine(p.PlayerName);
}
List<Player> paired = new List<Player>();
paired = pairing(PlayList);
foreach (Player r in paired)
{
Console.WriteLine(r.PlayerName);
}
}
static List<Player> pairing(List<Player> players)
{
List<Player> pairingList = new List<Player>();
int n = 1;
bool failed = true;
List<Player> returnedList = new List<Player>();
while ((failed) && n <= players.Count - 1)
{
if (PairIsGood(players[0], players[n], 0))
{
Player p1 = new Player();
p1 = players[0];
Player p2 = new Player();
p2 = players[n];
if (players.Count <= 2)
{
returnedList.Add(p1);
returnedList.Add(p2);
failed = false;
}
else
{
List<Player> nextPairs = new List<Player>();
nextPairs = players;
nextPairs.RemoveAt(0);
nextPairs.RemoveAt(n-1);
returnedList = pairing(nextPairs);
Console.WriteLine(players.Count.ToString());
Console.WriteLine(nextPairs.Count.ToString());
if (returnedList.Count == 0)
{
failed = true;
n++;
}
else
{
returnedList.Add(p1);
returnedList.Add(p2);
failed = false;
}
}
}
else
{
n++;
}
}
return returnedList;
}
static bool PairIsGood(Player p1, Player p2, int round)
{
bool good = true;
foreach (int op in p1.OpList)
{
if (op == p2.PlayerID)
{
good = false;
}
}
return good;
}
}
}
List<Player> nextPairs = new List<Player>();
nextPairs = players;
nextPairs.RemoveAt(0);
nextPairs.RemoveAt(n-1);
您创建一个新的List<Player>
并将其分配给nextPairs
然后您可以有效地丢弃该新列表,而将
nextPairs
分配给players
。[
nextPairs
和players
现在都引用相同的列表,并且从nextPairs
中删除也会从players
中删除,因为它们是相同的列表。如果想要真正的独立副本,请查看
Array.Copy()
。>