Card shuffle code
-
- Posts: 13
- Joined: Fri Feb 06, 2015 6:49 am
- My devices: Iphone 5
Card shuffle code
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
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
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
-
- Posts: 13
- Joined: Fri Feb 06, 2015 6:49 am
- My devices: Iphone 5
Re: Card shuffle code
Thanks so much! Works great and saves time and processing power over a 2500 switch algorithm I was ysing