Try something like this:
static string[] cards = { "s1", "s2", "s3","s4","s5","m1", "m2", "m3","m4","m5", "k1", "k2", "k3","k4","k5", "RD", "RD", "RD" };
private static Dictionary<int, string[]> DealTheCards(int numberOfPlayers, int numberOfCardsPerPlayer)
{
var playerDict = new Dictionary<int, string[]>();
for(int i = 0; i < numberOfPlayers; i++)
{
string[] player = new string[numberOfCardsPerPlayer];
playerDict.Add(i, player);
}
var cardsList = cards.ToList();
var cardsNeeded = playerDict.Count() * numberOfCardsPerPlayer;
if(cardsNeeded > cards.Count())
{
Console.WriteLine("Not enough Cards");
}
else
{
for(int i = 0; i < numberOfCardsPerPlayer; i ++)
{
foreach(var player in playerDict)
{
var rand = new Random();
var x = rand.Next(cardsList.Count);
var card = cardsList.ElementAt(x);
cardsList.Remove(card);
player.Value[i] = card;
}
}
}
return playerDict;
}
This code is a bit more flexible. Simply call the method DealTheCards
from your code like:
var numberOfPlayer = 3;
var numberOfCardsPerPlayer = 6;
var playersCards = DealTheCards(numberOfPlayer, numberOfCardsPerPlayer);
The return object is a Dictionary
object with a zero-based index for each player (player1 has an index = 0, player2 index = 1...)
This code allows you to be a bit more flexible in the number of players and number of cards each player can have--you just need to be certain to have enough cards in the deck to distribute.
This code mimics what you would expect when the cards are being dealt:
The dealer would have the cards (outer for
loop). Foreach player a card would be selected (removed from the deck) and given to the player. Then the next card would be selected (removed from the deck) and given to the next player... until all the players receive a card and then we start at the first player, again...until each player has received the number of cards that each player should have.
Note:
There is some criticism of how good Random
is at randomizing. There are other methods, but this should be sufficient for your application. Substituting a different randomizer should not be difficult.
Also:
The methods are static
because I set this up for a console application.
Please let me know if you have any questions.