I have pored over C# documentation and I have not found an actual method called Shuffle()
, but I wanted an implementation that at least came close to looking and feeling like a built-in method called Shuffle()
and also I knew I was going to have to manually put together the actual logic to do the shuffling or randomizing.
This is where I learned about the Fisher-Yates approach and that lead me to this particular post with a solution that I favor by grenade:
Unfortunately, I cannot seem to get this solution working for me. No matter how I configure it, I always end up with this error:
error CS1501: No overload for method 'Shuffle' takes '0' arguments
if I want to maintain the solution in this manner:
using System;
using System.Collections.Generic;
class Program
{
public static void Main()
{
// List<Deck> deck = new List<Deck>();
Deck deck = new Deck();
deck.Shuffle();
System.Console.WriteLine(deck);
}
}
public class Deck {
public List<Card> Cards = new List<Card>();
public Deck() {
string[] ranks = { "Ace", "Two", "Three", "Four", "Five" };
string[] suits = { "Diamonds", "Hearts", "Clubs", "Spades" };
foreach (string suit in suits) {
foreach (string rank in ranks) {
Card card = new Card(rank, suit);
Cards.Add(card);
}
}
}
public override string ToString()
{
string s = "[";
foreach (var card in Cards) {
s += card.ToString() + ", ";
}
s += "]";
return s;
}
private static Random rng = new Random();
public static void Shuffle<T>(IList<T> list)
{
int n = list.Count;
while (n > 1) {
n--;
int k = rng.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
}
public class Card {
// properties
public string suit { get; set; }
public string rank { get; set; }
public override string ToString()
{
return $"{rank} of {suit}";
}
public Card(string rank, string suit){
//initializations
this.rank = rank;
this.suit = suit;
}
}
It has the look and feel of working with a built-in method, but that error is telling me I need to pass something into Shuffle()
because I declared it like so: public static void Shuffle<T>(IList<T> list)
, and no matter what I attempt to pass into it, it just leads to another error.
So then if I go with this one:
class Program
{
public static void Main()
{
List<Deck> deck = new List<Deck>();
// Deck deck = new Deck();
deck.Shuffle();
System.Console.WriteLine(deck);
}
}
I am told Shuffle is not a method:
error CS1061: Type
System.Collections.Generic.List' does not contain a definition for Shuffle' and no extension method
Shuffle' of type System.Collections.Generic.List<Deck>' could be found.
and I know this, but then how is this working for grenade? What am I missing aside from some years of experience with this?