【发布时间】:2013-01-06 20:39:46
【问题描述】:
我正在编写一个多人游戏,其中每个玩家必须与组中的每个玩家只玩一次。即,如果您有 3 名玩家:Joe、Mary 和 Peter,则这些组合将是:Joe & Mary、Joe & Peter 和 Mary & Peter。
计算轮数的代码非常简单。由于轮数等于n! /r! * (n - r)!其中 n 等于玩家人数,r 等于 2(因为游戏每轮有 2 名玩家进行)。
public int factorial(int n)
{
if (n == 0)
return 1;
return n * factorial(n - 1);
}
public int calcNoOfRounds()
{
return factorial(noOfPlayers) / (factorial(2) * factorial(noOfPlayers -2));
}
但是,我坚持想出一种有效的方法来返回实际的玩家组合。我尝试了以下代码。它可以工作,但是它太手动了,有些事情我想改进。在这段代码中,我将 p1 vs p2、p2 vs p3、p3 vs p4 ... p(n-1) vs p(n) 配对。然后我从第 3 名球员开始,将这些球员与上述所有球员进行匹配,除了他们之前的球员,即 p3 vs p1、p4 vs p1、p4 vs p2、p5 vs p1、p5 vs p2、p5 vs p3 等。 . 你觉得我能做得更好吗?
public void calcPlayerCombinations()
{
List<string> playerNames = new List<string>();
for (int i = 0; i < noOfPlayers; i++)
{
playerNames.Add(players[i].PlayerName);
}
for (int i = 0; i < noOfPlayers - 1; i++)
{
playerCombinations.Add(playerNames[i] + " " + playerNames[i + 1]);
}
for (int j = 3; j <= noOfPlayers; j++)
{
int counter = 1;
do
{
playerCombinations.Add(playerNames[j -1] + " " + playerNames[counter -1]);
counter++;
} while (counter != (j - 1));
}
}
我不喜欢这样,因为如果游戏真的在玩,你希望同一个玩家连续玩 6 场比赛吗?我可以随机选择一个组合进行一轮是的,但我仍然想知道更好的方法以供将来参考。
感谢您的帮助!
【问题讨论】:
标签: c# algorithm combinations