Hi there,
I'm back to doing some coding and needed to remember how to shuffle a deck of cards. I finally remembered how from my old Atari Basic days. Here is a commented code snippet explaining the process. (Note this is not original code by me, but rather something from the good old days and I do not remember the original programmer.)
REM Let's build and shuffle a deck of cards..
DIM deck(53) `First we create an array with 52 spaces (+1 to avoid using '0' as the first card).
for cards=1 to 52 `this little for/next loop fills the deck(xx) with values 1 to 52
deck(cards)=cards
next cards
REM Now that we have a deck and it has 52 cards we will shuffle it
for s=52 to 1 step -1
random_index=rnd(s)+1 `this gives us a random number between 1 and 52
tmp=deck(random_index) `we pull that randon card and store it in tmp
deck(random_index)=deck(s) `we then transfer the '52nd' card to the random_index position..
deck(s)=tmp `then store the tmp card in the '52nd' slot
next s `Since we now process the for/next, the 52nd slot is 'protected'.
`The next loop will give a rnd # between 1 and 51
Rem There you have it, a deck of 52 cards all shuffled up.
I hope this code snippet helps. Oh, and the 'size' of the deck can be mush larger if needed.
Cheers!
P.S. here is a small program with the routine as a function to test the shuffle code.
REM Let's build and shuffle a deck of cards..
DIM deck(53) `First we create an array with 52 spaces (+1 to avoid using '0').
for cards=1 to 52 `this little for/next loop fills the deck(xx) with values 1 to 52
deck(cards)=cards
next cards
do
text 0,0,"Each press of the left Mouse button will shuffle and view the results."
if mouseclick()=1
cls
shuffle_deck()
show_results()
while mouseclick()=1
donothing=0
endwhile
endif
loop
function show_results()
c=1
for x=0 to 12
for y=0 to 3
text (x*32)+32,(y*32)+32,str$(deck(c))+" "
c=c+1
next y
next x
endfunction
function shuffle_deck()
for s=52 to 1 step -1
random_index=rnd(s)+1
tmp=deck(random_index)
deck(random_index)=deck(s)
deck(s)=tmp
next s
endfunction
have a great day.