费舍尔·耶茨在牌桌上的洗牌 [英] Fisher Yates Shuffle on a Cards List

查看:80
本文介绍了费舍尔·耶茨在牌桌上的洗牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在卡片列表上进行费舍尔·耶茨(Fisher Yates)的洗牌.我曾在论坛上搜寻过,Fisher Yates的唯一实现是使用如下所示的普通int数组

I'm trying to do the Fisher Yates shuffle on a list of Cards. I've scoured forums and the only implementation of Fisher Yates is with normal int arrays like below

for (int i = length - 1; i > 0; i--)
{
  int j = random.Next(i + 1);
  int temp = array[i];
  array[i] = array[j];
  array[j] = temp;
}

这很合理,我的麻烦是我没有真正看到如何将这种逻辑转换为我拥有的事物的方式,在实现此目标方面的任何帮助将不胜感激.相关代码如下:

Which makes sense just fine, my trouble is I don't really see how to convert that logic to the way I have things, any help in accomplishing this would be greatly appreciated. Relevant code below:

public struct Card : IComparable<Card>
{
  public Rank Rank { get; private set; }
  public Suit Suit { get; private set; }

  public Card(Rank rank, Suit suit) : this()
  {
    Rank = rank;
    Suit = suit;
  }

  public override string ToString()
  {
    return string.Format("{0:x} {1}", (char) Suit, Rank);
  }
}
public enum Suit { Spades = 9824, Clubs = 9827, Hearts = 9829, Diamonds = 9830 }
public enum Rank { Ace, Deuce, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King }

public class Deck
{
  public List<Card> Cards { get; private set; }

  public Deck()
  {
    foreach (Rank rank in Enum.GetValues(typeof(Rank)))
    {
      foreach (Suit suit in Enum.GetValues(typeof(Suit)))
      {
        Card card = new Card(rank, suit);
        Cards.Add(card);
      }
    }
  }
  public Deck(List<Card> cardDeck)
  {
    Cards = cardDeck;
  }
  public void Shuffle()
  {  //???? I don't know how I would apply the Fisher Yates logic to here
     //since all other programs just use normal int arrays
  . . .

感谢所有帮助.

推荐答案

当然逻辑完全相同吗?唯一的不同是,您从集合中读取的是 Card ,而不是 int ,即

Surely the logic is exactly the same? The only different is that you are reading a Card from your collection rather than an int, i.e.

for (int i = Cards.Count - 1; i > 0; i--)
{
    int j = random.Next(i + 1);
    Card temp = Cards[i]; // Notice the change on this line
    Cards[i] = Cards[j];
    Cards[j] = temp;
}

修复注释中提到的编程错误后,此实现似乎对我有用.

After fixing up the programming errors mentioned in the comment, this implementation seems to work for me.

这篇关于费舍尔·耶茨在牌桌上的洗牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆