Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Brute force Card shake method in C#

Tags:

c#

windows

bots

I’m making a bot that can test some card tactics on a game, the bot works but I have one problem. My card shake method is not very good. I shake the cards this way:

        public void ShuffelDeck()
        {
            for (int i = 0; i < 5; i++)
                Cards = ShuffelCards(Cards);
        }

        private ArrayList ShuffelCards(ArrayList Cards)
        {
            ArrayList ShuffedCards = new ArrayList();

            Random SeedCreator = new Random();
            Random RandomNumberCreator = new Random(SeedCreator.Next());

            while (Cards.Count != 0)
            {
                int RandomNumber = RandomNumberCreator.Next(0, Cards.Count);
                ShuffedCards.Insert(ShuffedCards.Count, Cards[RandomNumber]);
                Cards.RemoveAt(RandomNumber);
            }

            return ShuffedCards; 
        }

The problem is when I calculate without a pause between the card shake process , a few players will win a lot of games. For example

Player 1: 8 games
Player 2: 2 games
Player 3: 0 games
Player 4: 0 games

But when I add a dialog before the card shake process the wins will get spread over the players:

Player 1: 3 games
Player 2: 2 games
Player 3: 1 game
Player 4: 4 games

I guess that the Random class is not good enough for a brute force like this. How can I shuffle the cards without a problem like this?

Update: I already tried to use 1 Random class, and I also tried to shake the cards only once.

like image 475
Laurence Avatar asked Jul 25 '12 18:07

Laurence


1 Answers

When you create a new instance of the Random class it is seeded with the current time, but the current time it's seeded with only has precision down to 16 ms, meaning if you create a new Random class within the same 16 millisecond interval (that's a long time for a computer) as another instance you'll get the same random number sequence.

One good solution is to just ensure you aren't creating so many new Randoms. Create one, once, and pass it into the shuffle cards method, or create a static random that is just accessible in a lot of places (just remember that it's not thread safe).

On a side note, for your actual shuffling algorithm it's pretty good. You could make one improvement though. Rather than adding the chosen element to the end and removing it from the middle, you can just swap the element at the end with the one in the middle. This is more efficient since removing from the middle of a List isn't an efficient operation. Additionally, rather than picking a random number between 0 and the size, pick a number between 0 and (size minus the number of the current iteration). See the wikipedia article on the subject for more details on the algorithm.

like image 146
Servy Avatar answered Oct 21 '22 00:10

Servy