c# - C#:协助使这种 shuffle 方法工作
问题描述
我仔细Shuffle()
研究了 C# 文档,但Shuffle()
我还没有找到一个名为进行洗牌或随机化的实际逻辑。
这是我了解 Fisher-Yates 方法的地方,这使我找到了这篇特别的帖子,并提出了一个我喜欢手榴弹的解决方案:
不幸的是,我似乎无法让这个解决方案为我工作。无论我如何配置它,我总是会遇到这个错误:
error CS1501: No overload for method 'Shuffle' takes '0' arguments
如果我想以这种方式维护解决方案:
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;
}
}
它具有使用内置方法的外观和感觉,但是该错误告诉我我需要传递一些东西,Shuffle()
因为我这样声明它:public static void Shuffle<T>(IList<T> list)
,无论我尝试传递什么,它都会导致另一个错误。
那么,如果我选择这个:
class Program
{
public static void Main()
{
List<Deck> deck = new List<Deck>();
// Deck deck = new Deck();
deck.Shuffle();
System.Console.WriteLine(deck);
}
}
我被告知 Shuffle 不是一种方法:
error CS1061: Type
System.Collections.Generic.List' 不包含Shuffle' and no extension method
Shuffle' 类型的定义System.Collections.Generic.List<Deck>' could be found.
我知道这一点,但是这对手榴弹有什么作用?除了几年的经验之外,我还缺少什么?
解决方案
原型为Shuffle
public static void Shuffle<T>(IList<T> list)
与您呼入的方式不同main
deck.Shuffle();
这就是您收到CS1051错误的原因。首先修复该错误,然后它也会为您工作。
推荐阅读
- pandas - 如何用现有列值替换 DataFrame 列的 NaN 值?
- cmd - 如何将文件中的一些文本保存到cmd中的变量?
- javascript - 在 FlaskSocketIO 聊天中设置动态聊天室
- apache-spark - 从 cosmos 到 ADLS 的数据归档
- javascript - 如何根据人员数组长度的可分值准备数组?
- java - java - 如何在Java中使用HTTPDELETE作为RequestBody发送列表参数
- visual-studio-code - 如何选择 TM_DIRECTORY 变量的一部分?
- azure-devops - 在 Azure DevOps 构建管道中传递 NuGet 'Pack' 参数
- php - Foreach Json 数组
- android - 从 Flavor 和 BuildType 添加 cppflags 然后在我的 CmakeList 中访问它们