This question has already been answered:

It is necessary to mix the array.

Program class:

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Poker { class Program { static void Main() { Deck d = new Deck(); d.PrintCards(); Console.ReadKey(); } } } 

Deck class:

 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Poker { class Deck { string[] ranks = new string[13]; string[] suits = new string[4]; public Card[] cards = new Card[52]; public Deck() { for (int a = 0; a < 13; a++) { for (int b = 0; b < 4; b++) { cards[b * 13 + a] = new Card(); cards[b * 13 + a].Rank = a; cards[b * 13 + a].Suit = b; } } ranks[0] = "2"; ranks[1] = "3"; ranks[2] = "4"; ranks[3] = "5"; ranks[4] = "6"; ranks[5] = "7"; ranks[6] = "8"; ranks[7] = "9"; ranks[8] = "10"; ranks[9] = "J"; ranks[10] = "Q"; ranks[11] = "K"; ranks[12] = "A"; suits[0] = "c"; suits[1] = "h"; suits[2] = "s"; suits[3] = "d"; } public void ShuffleDeck() { int x; Card tempcard; for (int a = 0; a < 52; a++) { Random rand = new Random(); x = rand.Next(1, 100); tempcard = cards[a]; cards[a] = cards[x]; cards[x] = tempcard; } } public void PrintCards() { for (int a = 0; a < 52; a++) { Console.Write(ranks[cards[a].Rank] + suits[cards[a].Suit] + " "); } } } } 

In the ShuffleDeck method ShuffleDeck should be a shuffle of the deck, but it does not work.

Reported as a duplicate by PashaPash member ♦ c # 24 Jul '16 at 17:50 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • Perhaps an exception is thrown that you "forgot" to mention? For example, ArrayIndexOutOfBoundsException due to the fact that x takes values ​​from 1 to 100, while cards only 52 elements. - Regent
  • And still it is worth getting rid of the "magic constants" 4 , 13 and 52 scattered around the code. Yes, it is unlikely that once you will have not 4 suits with 13 cards in each, but nobody canceled a good programming style. - Regent
  • In what sense? I only have a deck of 2c, 3c, 4c, and so on. Here it is necessary to mix only. - Vladimir

1 answer 1

Your implementation of the algorithm refers to an array at a random index from 0 to 99. While there are only 52 elements in the array. Will fall. It does not fall only because the ShuffleDeck method is never called for by you.

The standard way of mixing an array is the Fisher – Yets Shuffle.

 static class RandomExtensions { public static void Shuffle<T>(this Random rng, T[] array) { int n = array.Length; while (n > 1) { int k = rng.Next(n--); T temp = array[n]; array[n] = array[k]; array[k] = temp; } } } 

use as

 var rand = new Random(); rand.Shuffle(cards); 

Apparently, it was you who tried to implement it, just a little bit wrong with the indexes.