HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Helper method to shuffle cards list for online gaming

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
gamingmethodhelpercardsonlineshuffleforlist

Problem

I have written this code to shuffle a deck of cards. I would like to hear your inputs.

public static class Helper
{

    public static Int32 GetRandomNo(this RNGCryptoServiceProvider rng, byte[] data)
    {
        rng.GetBytes(data);
        var randomNo = BitConverter.ToInt32(data, 0);
        return randomNo;
    }

    public static void Shuffle(this List source)
    {
        using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
        {
            // Buffer storage.
            byte[] data = new byte[4];

            source =
                source.Select(element => new {element, randomValue = rng.GetRandomNo(data)})
                    .OrderBy(entry => entry.randomValue)
                    .Select(entry => entry.element)
                    .ToList();
        }
    }
}

Solution

4 bytes is only 4,294,967,296

Consider there are 52! possible shuffles = 8 * 10^67

Use a proper shuffle like Fisher Yates. You get a proper shuffle with only 0-51 random. Also shuffle from the prior shuffle (not a sorted deck). If you look closely Fisher Yates it produces exactly 52! deals. It is perfect.

I am not sure about your algorithm but I think the problem is that it will produce too many shuffles and they will not have uniform distribution. I think it will produce 52^52 deals.

A perfect random with a less than perfect algorithm is a bigger vulnerability than a perfect algorithm and a less than perfect random.

You can use the regular Random and a proper algorithm and not be exploited unless they know the seed. But it does not hurt to use RNGCryptoServiceProvider.

Poker security

Context

StackExchange Code Review Q#160566, answer score: 4

Revisions (0)

No revisions yet.