Fisher Yates Shuffle on a Cards List

后端 未结 2 2027
孤独总比滥情好
孤独总比滥情好 2020-12-22 08:28

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

相关标签:
2条回答
  • 2020-12-22 09:10

    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.

    0 讨论(0)
  • 2020-12-22 09:18

    Having actually done this before (albeit using my own shuffle, still based on ints), I would do this:

    1. Add a constructor to the card class that takes an int. Its pretty easy to map the 52 cards of a deck to the numbers 0-51, so I'll leave that to you. Note: This becomes a lot easier if you map the suits to 0-3, instead of the seemingly random numbers you have chosen.

    2. Create a starting "deck" using a for loop to generate all 52 cards.

    3. Run the shuffle on this created list.

    0 讨论(0)
提交回复
热议问题