Page 1 of 1

Card shuffle code

Posted: Sat Feb 21, 2015 7:59 am
by Lauderdale
Anyone have code or an approach to shuffle a 52 card deck. I don't want it to take forever by picking random cards that have already been shuffled.

Re: Card shuffle code

Posted: Tue Feb 24, 2015 9:07 pm
by Dalede
Here is how to go about it. Make an array with 52 elements (0 to 51 or 1 to 52). It can be strings or the numbers from 1 to 52. Adjust the range as needed. Then write
DIM cards(52) ; or Cards$(52) or 51 if you start at 0
Fill the array with data statements for card such as HA, H2, ..., SA, S2, (suit and value) or the numbers 1 to 52 using a for loop (for e=1 to 52!Cards(e)=e!next e)
FOR E=52 to 2 step -1
A=RND(E) ; pick a number from 0 to 51 or you can add 1 to pick from 1 to 52.
TEMP = cards(E) ; save the last value, remember each time this will be a smaller number.
cards(E)=Cards(A)
cards(A)=TEMP
next E

If you have numbers then use the numbers as indexes into an array of cards or if you use strings then you have sorted the deck directly. The idea is that you go thru the list once rearranging the numbers based on a random index into the list. This is a rough approach without writing all the code for you.

Dale

Re: Card shuffle code

Posted: Wed Feb 25, 2015 5:40 pm
by Lauderdale
Thanks so much! Works great and saves time and processing power over a 2500 switch algorithm I was ysing