tags:

views:

161

answers:

4

This C# program is suppose to be a blackjack program but I need to 'SHUFFLE' the card and just display the 'HAND'

The rest i think I can manage... can someone help me?

A: 

I think it has been already covered here.

cement
You should have added this a comment rather than as an answer.
ChrisF
@ChrisF: I would agree that this is more comment-like, but are you aware of any actual guidelines as to what makes a comment rather than an answer? I tried looking for it on meta but couldn't find anything appropriate.
Patrick
@Patrick - maybe we need some to go with the question asking guidelines (who's link escapes me right now)
ChrisF
A: 

One way to shuffle is to create new array and move the cards into that array in a random order

List<Card> unshuffled = new List<Card>(pack);
pack = new Card[NUM_CARDS];
Random r = new Random()
for(int card = 0; card < NUM_CARDS; card++)
{
    pack[card] = unshuffled[r.Next(0, unshuffled.Count -1)];
    unshuffled.remove(pack[card]);
}

You might want to make the Random instance global, as creating a new random each time reduces entropy somewhat. This might not be important if you are not shuffling a lot.

Matt Ellen
Thank You So much.. this will help :D it works
Sydney
+1  A: 

I would recommend just switching each element to random other, heres how:

private void switchElements(Card[] pack, int nr_1, int nr_2) {
    Card temp = pack[nr_1];
    pack[nr_1] = pack[nr_2];
    pack[nr_2] = temp;
}

public void shuffle(Card[] pack) {
    for (int i = pack.length - 1; i > 0; i--) 
        switchElements(pack, i,random.Next(0,i));
}
Margus
Um, wouldn't that guarantee that whichever card is last in pack[] before calling shuffle cannot possibly be the last card in pack[] after shuffle?
Damien_The_Unbeliever
This is as simple as: pick a random card and put it on deck 2, until you have done that for all the cards in deck 1. Only difference is that there is no deck 2, picked cards are stored on top of deck 1. This is also how Java **Collections.shuffle()** works.
Margus
A: 

You could "shuffle" a pack with something as simple as:

var shuffled = pack.OrderBy(c => random.NextDouble());
Ed Courtenay
Could this cause an infinite loop? Would depend on which type of sort LINQ is using here.
Bryan
No, it won't cause an infinite loop - it's definitely not an optimal solution either, but given the level of the homework assigned (although it seems the original source has now been removed) it would have been simple to implement as opposed to Fisher-Yates
Ed Courtenay