高效的方式返回球员组合

时间:2013-01-06 09:56:23

标签: c# algorithm combinations

我正在编写一个多人游戏,其中每个玩家必须只与其组中的每个玩家玩一次。即如果你有3名球员:Joe,Mary和Peter,这些将是组合:Joe&玛丽,乔和&彼得和玛丽&彼得。

计算轮数的代码非常简单。由于轮次数等于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与p2,p2与p3,p3与p4 ... p(n-1)与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场比赛?我可以随机选择一个组合进行一轮肯定,但是,我想知道一个更好的方法供将来参考。

感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

为什么你不会将每个玩家(在配对中作为“第一个”)与每个玩家配对(比如“第二个”)?例如:

public static IEnumerable<string> PairPlayers(List<string> players)
{
    for (int i = 0; i < players.Count - 1; i++)
    {
        for (int j = i + 1; j < players.Count; j++)
        {
            yield return players[i] + " " + players[j];
        }
    }
}

(如果你愿意的话,显然你也可以急切地这样做。)

虽然我可能误解了这些要求。

答案 1 :(得分:1)

此示例显示如何将播放器列表用作队列。当一名球员参加比赛时,他们被放到后面并且最不可能再次被选中。它还展示了如何做Jon Skeet所做的但是渴望(没有yield)。

using System;
using System.Collections.Generic;
using System.Linq;

namespace SOPlayersOrder
{
    class Program
    {
        /// <summary>
        /// Represents a match up between two players.
        /// It is tempting to use strings for everything, but don't do it,
        /// you'll only end up having to split those strings and you will
        /// not benefit from type safety.
        /// </summary>
        public class MatchUp
        {
            public string Player1 { get; set; }
            public string Player2 { get; set; }

            public override string ToString()
            {
                return string.Format("{0} vs {1}", Player1, Player2);
            }
        }

        public static IEnumerable<MatchUp> PairPlayers(List<string> players)
        {
            var results = new List<MatchUp>();
            for (int i = 0; i < players.Count - 1; i++)
            {
                for (int j = i + 1; j < players.Count; j++)
                {
                    var matchup = new MatchUp { Player1 = players[i], Player2 = players[j] };
                    //yield return matchup; //this is how Jon Skeet suggested, I am showing you "eager" evaluation
                    results.Add(matchup);
                }
            }
            return results;
        }

        public static IEnumerable<MatchUp> OrganiseGames(IEnumerable<string> players, IEnumerable<MatchUp> games)
        {
            var results = new List<MatchUp>();
            //a list that we will treat as a queue - most recently played at the back of the queue
            var playerStack = new List<string>(players);
            //a list that we can modify
            var gamesList = new List<MatchUp>(games);
            while (gamesList.Count > 0)
            {
                //find a game for the top player on the stack
                var player1 = playerStack.First();
                var player2 = playerStack.Skip(1).First();
                //the players are in the order of least recently played first
                MatchUp matchUp = FindFirstAvailableGame(playerStack, gamesList);
                //drop the players that just played to the back of the list
                playerStack.Remove(matchUp.Player1);
                playerStack.Remove(matchUp.Player2);
                playerStack.Add(matchUp.Player1);
                playerStack.Add(matchUp.Player2);
                //remove that pairing
                gamesList.Remove(matchUp);
                //yield return matchUp; //optional way of doing this
                results.Add(matchUp);
            }
            return results;
        }

        private static MatchUp FindFirstAvailableGame(List<string> players, List<MatchUp> gamesList)
        {            
            for (int i = 0; i < players.Count - 1; i++)
            {
                for (int j = i + 1; j < players.Count; j++)
                {
                    var game = gamesList.FirstOrDefault(g => g.Player1 == players[i] && g.Player2 == players[j] ||
                                                             g.Player2 == players[i] && g.Player1 == players[j]);
                    if (game != null) return game;
                }
            }
            throw new Exception("Didn't find a game");
        }

        static void Main(string[] args)
        {
            var players = new List<string>(new []{"A","B","C","D","E"});
            var allGames = new List<MatchUp>(PairPlayers(players));

            Console.WriteLine("Unorganised");

            foreach (var game in allGames)
            {
                Console.WriteLine(game);
            }

            Console.WriteLine("Organised");

            foreach (var game in OrganiseGames(players, allGames))
            {
                Console.WriteLine(game);
            }

            Console.ReadLine();
        }
    }
}