Hey guys, I was wondering if there was a more efficient way to shuffle a Stack. This is the code I have now based on the couple of solutions I’ve found so far, but is there a better way to do this?
public void Shuffle(Deck deck)
{
var arr = deck.cards.ToArray();
for (var i = arr.Length - 1; i > 0; i--)
{
var temp = arr[i];
var index = r.Next(0, i + 1);
arr[i] = arr[index];
arr[index] = temp;
}
deck.cards = new Stack<Card>(arr);
}
AFAICT that’s just a Fisher-Yates you have going there… the only thing that would be more efficient is not to pluck it out into an array, just shuffle it right in place in the collection you have.
EDIT: I’m not sure if the Stack API lets you get at arbitrary items. Any reason you’re using a Stack? A Stack of cards in real life isn’t really a stack: your hands have an API where you can pick it up and take any particular card… I always just store cards in List() because that’s just way more flexible for everybody involved, all the code up and down the line.
Putting on my OO hat, it seems like “Shuffle” should just be a method in your Deck object… but making separate utilities is fair too.
I’m using Stacks just to experiment with them since I’m trying to learn how to code, I know it’s not an efficient way to represent a deck, but in my head it was the first thing I thought of since I can draw by popping, add a card by pushing, and peek the top, etc.
And thank you, I moved the method to the Deck class.