shuffling deck of cards

  • Thread starter Thread starter WStoreyII
  • Start date Start date
W

WStoreyII

i am trying to make a sub that will shuffle a set of numbers

i have tried using the random object but i keep getting repeats

how do i get rid of the repeats

WStoreyII
 
Hi WStoryII

Use the last environment.tickcount

Multiply the last part with the first part or whatever

Just my thoughts

Cor
 
Here is a way that should work:

-Generate a random number between 1 and the number of items in the
collection
-Add the item at that index to another collection
-Remove that item from the original collection
-Repeat until you have removed all items from original collection


Brian Davis
http://www.knowdotnet.com
 
Here we go again :-)

Shuffling seems to lead people to making a common coding mistake. The
algorithm have been around for decades and I just looked for the one I wrote
in Clipper 15 years ago (thought I might post it) but I couldn't find it.

In any case... fundamentally you have an array which represents all your
cards. You choose a random card between 1 and 52 and swap that card with
the one in the first element of the array. Then you choose a random card
(and this is the important part) from between 2 and 52. You swap this one
with the card in the second element. Then proceed on with 3, 4, 5, etc.
Every card is given a chance to move and each position is filled only once.

There can't be any repeats as the number of remaining cards always
decreases.

Tom
 
Brian Davis said:
-Add the item at that index to another collection
-Remove that item from the original collection
-Repeat until you have removed all items from original collection

Hi Brian... not a big deal but you don't need to duplicate the collection
and incur that overhead particularly if it is a simple array of integers.
You only need a single temporary variable to hold the value that is being
swapped.

I decided to write it in VB.Net so if the OP wants me to I can post the
code. I'd rather he post his code and that we make suggestions for
improvement however.

Tom
 
WStoreyII said:
i am trying to make a sub that will shuffle a set of numbers

i have tried using the random object but i keep getting repeats

how do i get rid of the repeats

WStoreyII

Could you give a little more info?

Do you have an array of int's? Or are you just trying to populate an array?
 
Yeah, it was definitely a bad idea to create another collection. My initial
thought on it was that if the data were in a collection, the Item property
would be ReadOnly, so you could not just swap values. I think that you
could do it by storing the value in a temporary variable, removing it from
the collection, then adding it back to the end of the collection. That
would prevent the creation of another collection, but it would still be much
slower than dealing with arrays.


Brian Davis
http://www.knowdotnet.com
 
Back
Top