Board Logo
« SHUFFLING (Cards, Questions, Images) »

Welcome Guest. Please Login or Register.
Jan 18th, 2018, 3:50pm


Conforums Terms of Service | Membership Rules | Home | Search | Recent Posts | Notification | Format Your Message | Installation FAQ

This board is not meant for general discussion, it is meant for posting articles to help others.
For general discussions use the appropriate board, which best describes your problem area.

« Previous Topic | Next Topic »
Pages: 1 2 3  Notify Send Topic Print
 veryhotthread  Author  Topic: SHUFFLING (Cards, Questions, Images)  (Read 1867 times)
Welopez
Moderator
ImageImageImageImageImage


member is offline

Avatar

Never let your beliefs get in the way of learning.


PM

Gender: Male
Posts: 4407
xx SHUFFLING (Cards, Questions, Images)
« Thread started on: Jan 19th, 2011, 09:03am »

SHUFFLING (Cards, Questions, Images)

by Welopez

One of the things I enjoy about these forums is learning new (or previously unknown to me) ways to accomplish simple tasks. Lots of people ask "How can I shuffle a deck with no repeats?" Or questions for a quiz, or images for a slide show, etc, etc. I've written several tutorials on this subject, and thought it would be great to write a new one for this procedure.

The other day I was over on the LB Forum where a person asked a similar question. Sam Wetterlin posted a response that I had not seen before, so I tried it out and it was simpler than any other method I've seen. Of course, I wanted to post it in the Just Basic forum, but first I had to massage the LB code which used the built-in SORT function of LB, so that JB users could take advantage of the technique.

How does it work? Let's try this short snippet:

Code:

FOR k=1 TO 25
PRINT RND(0)
NEXT k

END

 


As you can see, RND(0) produces numbers greater than zero, but less than one. If we write this RND(0) value on the back of each card, then sort the cards into order according to the RND(0) value, we will achieve a "pseudo-random" shuffle. Will the random numbers repeat? Eventually they will, but the odds are 52 out of 99,999,999+ (1,923,076+ to 1) they will not. The big brains with PhD after their name will tell you that in any group of 30 persons, it is highly probable two will have the same birthday, even though there are 365.25 days in a year. If there were 99,999,999+ days in a year, I think the odds would be much steeper, like playing Russian Roulette with a revolver having 1,000,000 cylinders, of which only one has a deadly bullet. Okay, I still wouldn't want to play, but you can appreciate the odds would be only 1 in 1,000,000 that the results would ruin your whole day, in fact, your whole life!

We first need a double-dimensioned array. The first value, or second, depending upon how you write your code, holds the numbers for 52 cards in sequential value. The second dimension holds a random value achieved by RND(0). Keep in mind, the RND(0) function returns an 8 digit decimal value, for a possible 99,999,999+ results. Then the array of RND(0) values is sorted in ascending or descending order, the order makes no difference. We keep the number for cards aligned with the RND(0) value after sorting, then the sorted number of cards can be printed out. The program looks like this:

Code:

'by Sam Wetterlin, Jan 13, 2011
'adapted for JB by Welopez

dim Order(100,2) 'array for ordered and random numbers
for i=1 to 100
Order(i,1)=i
Order(i,2)=rnd(1)
next i

sort Order(), 1,100,2

for i=1 to 100
print USING("####",Order(i,1)), Order(i,2)
next i

END
  


Is that simple or what? The work is done in six lines, including the SORT function. The final three lines are merely to prove the deck has been randomly sorted. If you run that snippet 100 times and examine the results each time, you will find 100 different results.

Okay, all well and good, but JB does not have a SORT function. No problem, simply write one which produces the same results. After all, it is highly desirable to have 99,999,999+ possible shuffles for a 52 card deck. Or for a list of 100 test questions, or 500 images for a slide show.

Sorting a double-dimensioned array is no different than any other sort using JB. You can use any of the common sort algorithms you are familiar with to sort our double-dimensioned array, the only requirement is that you keep RND(0) values aligned with the number to identify individual cards. Here is my version of shuffling written for JB:

Code:

INPUT "Enter number of cards: "; cards

DIM theDeck(cards, 2)

FOR k=1 TO cards
    theDeck(k, 1)= RND(0)
    theDeck(k, 2)= k
NEXT k

PRINT "The unsorted cards..."
FOR k=1 to cards
    PRINT USING("####", theDeck(k,2));
    n=n+1
    IF n=10 THEN n=0: PRINT
NEXT k
n=0
PRINT
PRINT
PRINT "The shuffled cards..."

CALL shuffle cards

FOR k=1 TO cards
    PRINT USING("####", theDeck(k, 2));
    n=n+1
    IF n=10 THEN n=0: PRINT
NEXT k

END

SUB shuffle cards
    FOR i=1 TO cards
        FOR j=1 TO (cards-1)
            IF theDeck(j,1)>theDeck((j+1),1) THEN
            theDeck(0,1)=theDeck(j,1)
            theDeck(0,2)=theDeck(j,2)
            theDeck(j,1)=theDeck((j+1),1)
            theDeck(j,2)=theDeck((j+1),2)
            theDeck((j+1),1)=theDeck(0,1)
            theDeck((j+1),2)=theDeck(0,2)
            END IF
        NEXT j
    NEXT i
END SUB

 


Creating the array of numbers for each card and the RND(0) values is the same as Sam's code for LB. Then I wrote a SUB to accomplish sorting the RND(0) values, at the same time moving the card numbers to the second attribute for elements of the array. Same results as Sam's technique using LB. It would certainly be simpler to spend the few dollars needed to purchase LB, but half the fun of JB is writing code to produce the same effect as LB.

How will you use this for test questions? You will need a string array, and each element of the array will hold a question.
question$(1)="When was the first US congressional convention held?"
...
question$(20)="What is the address of our White House?"
...
question$(45)="What is the chemical composition for hydrochloric acid?"
...
question$(80)="What is the atomic element abbreviation for sodium?
... and so on.

When shuffling for test questions, you will need a third attribute to hold the answer for the questions. NOT a three dimensional array, but an array for x$(1,1) RND(0), x$(1,2) question$, x$(1,3) correct answer$. Shuffle the array by sorting x$(1,1) to display x$(1,2) to the user, then compare the user's answer to x$(1,3). Remember, Just Basic requires if any attribute of the array element is a string, the entire array must be a string.

For image paths, put RND(0) into x$(1,1) and the full path to the image into x$(1,2). Sort the array keying on x$(1,1) and print the image found in x$(1,2). N'est pas?

I hope this procedure will answer many of the questions JB users have. Good luck to you all!

« Last Edit: Jan 20th, 2011, 05:57am by Rod » User IP Logged

JB 1.01
Win7 64bit, 4 GB RAM, Pentium 6200@2.13 GHz (laptop)
WinXP, 1 GB RAM, Intel N270@1.6 GHz (netbook)
tsh73
JB-Supporter


member is offline

Avatar




PM

Gender: Male
Posts: 3636
xx Re: SHUFFLING (Cards, Questions, Images)
« Reply #1 on: Jan 20th, 2011, 01:24am »

Welopez,
the tutorial is nice (though it's definitely *simpler* in LB case wink )
but I really wonder what this supposed to mean (or where did you got that):
Quote:
Keep in mind, the RND(0) function returns an 8 digit decimal value, for a possible 99,999,999+


Since floating point numbers in JB/LB has 16 digits, truncating values at 8 digits doesn't look having much sence?

I run a test - renerated 100 000 random numbers, sorted them and printed minimal difference. On third try I got minimal difference 0.33306247e-10.
That means, there are two random numbers generated hat differ only after 10th digit.

EDIT
Also I can't quite understand this one:
Quote:
Will the cards repeat? Eventually they will

If there were no repeating cards in a deck, then how cards could repeat after shuffling?
Or something else was meant?
« Last Edit: Jan 20th, 2011, 01:31am by tsh73 » User IP Logged

Q: "And if I took your codes and compile them, and sell them for a profit"?
A: Go ahead. I had my share of good then I coded it for fun, if you can make better use of it - please do.
(enjoying JB 1.01 on WinXP, netbook and desktop)
Rod
Administrator
ImageImageImageImageImage


member is offline

Avatar

Graphics = Goosebumps!


PM

Gender: Male
Posts: 3151
xx Re: SHUFFLING (Cards, Questions, Images)
« Reply #2 on: Jan 20th, 2011, 06:03am »

I was impressed by the method. It took a moment or two to sink in but once I realised what was happening it seemed pretty smart. Essentially the rnd() numbers are decoupled from the card faces or elements you want to shuffle. It matters not that you might get a repeating rnd() value you simply cannot repeat a card face because they are only ever set once.

I took the liberty of changing "will the cards repeat" to "will the random numbers repeat" which is what I think Welopez intended.
User IP Logged

Welopez
Moderator
ImageImageImageImageImage


member is offline

Avatar

Never let your beliefs get in the way of learning.


PM

Gender: Male
Posts: 4407
xx Re: SHUFFLING (Cards, Questions, Images)
« Reply #3 on: Jan 20th, 2011, 09:15am »

To answer both questions...
  • 1. Yes, floating point decimals are stored as 16 digit fractions, but only the first 8 digits are displayed to the user. We have to accept on faith that 8 digits are further appended to the RND() value, because we can't see them. However, the user can see there can be 99,999,999 possibilities between .00000001 and .99999999. I was trying to avoid explaining color to a blind man, so I included the + to show there were more possibilities.

  • 2. Correct, Rod. There cannot possibly be a repeating identifier for a card, whether you have 52, 104, 156, or more, because the cards are "loaded" sequentially. You're right, the RND() "tag" associated with a card could possibly repeat, but then it's also possible a football sized meteor could drop squarely on my head at any time! It's possible, but highly improbable, and I am fearless!

My intent was to show this extremely simple, extremely fast method for shuffling "objects," no matter what they may be. I intend to use this method in my future programming efforts.

« Last Edit: Jan 20th, 2011, 09:17am by Welopez » User IP Logged

JB 1.01
Win7 64bit, 4 GB RAM, Pentium 6200@2.13 GHz (laptop)
WinXP, 1 GB RAM, Intel N270@1.6 GHz (netbook)
tsh73
JB-Supporter


member is offline

Avatar




PM

Gender: Male
Posts: 3636
xx Re: SHUFFLING (Cards, Questions, Images)
« Reply #4 on: Jan 20th, 2011, 2:51pm »

Quote:
My intent was to show this extremely simple, extremely fast method for shuffling "objects,"

It is simple for understanding, yes
But it is simple for realization only if you have sort routine for free (as with LB)

Now, let us think a bit - again - about "simple" and "fast"
We assign random ID's for cards, then sort routine swaps pair of cards till ID's came in order
Bubble sort have O(n^2) swaps, I believe quick sort has about O(n*ln(n)) swaps
But the point is, we do not need that order at all! ID's generated are completely random.

So if we swap each card to random position only ONCE, we'll get same pretty random shuffle, but with only 'n' swaps. And it bound to be faster then any JB sorting.

The code that does this is in reply #11 by DAVEG in the thread
Avoiding FIVE Aces in a RND(0) Deal
User IP Logged

Q: "And if I took your codes and compile them, and sell them for a profit"?
A: Go ahead. I had my share of good then I coded it for fun, if you can make better use of it - please do.
(enjoying JB 1.01 on WinXP, netbook and desktop)
tsh73
JB-Supporter


member is offline

Avatar




PM

Gender: Male
Posts: 3636
xx Re: SHUFFLING (Cards, Questions, Images)
« Reply #5 on: Jan 20th, 2011, 2:57pm »

Quote:
We have to accept on faith that 8 digits are further appended to the RND() value, because we can't see them.

Wrong.
We don't have to "to accept on faith" anything.
Especially anything we can check.
In this particular case,
  • we can see more then 8 digits if we use USING
  • we can test if difference between random numbers could be less then 1e-8 (I did.)

*very very sad*
« Last Edit: Jan 20th, 2011, 2:58pm by tsh73 » User IP Logged

Q: "And if I took your codes and compile them, and sell them for a profit"?
A: Go ahead. I had my share of good then I coded it for fun, if you can make better use of it - please do.
(enjoying JB 1.01 on WinXP, netbook and desktop)
tomc
Senior Member
ImageImageImageImageImage


member is offline

Avatar




PM


Posts: 590
xx Re: SHUFFLING (Cards, Questions, Images)
« Reply #6 on: Jan 25th, 2011, 11:16am »

I am truly delighted to see this method of shuffling (anything) cards. It makes a great deal of sense and one I can probably use in the future.
.
the discussion back and forth if a number should repeat (and the rarity of it) is not needed. Equal sort keys happens all the time, and commercial applications order equal keys by a known algorithm (handy to put back into original order) or randomly (used for speed).
.
The whole point is, this "alternate" method is easier then methods I have been using for 30 years !!!
User IP Logged

Gearce
Full Member
ImageImageImageImage


member is offline

Avatar




PM

Gender: Male
Posts: 153
xx Re: SHUFFLING (Cards, Questions, Images)
« Reply #7 on: Mar 2nd, 2012, 5:23pm »

Welopez

An interesting shuffle. Here's one which I use mostly in my programmes.

Code:
rem  =========================================================================
rem    Initialise counters
rem  =========================================================================
    cardpack=52

rem  =========================================================================
rem     Declare array/s
rem  =========================================================================
    dim randomseries(cardpack)

rem  =========================================================================
rem    Shuffle cards and write results to screen
rem  =========================================================================
    for nextnumber=1  to cardpack
        do
            x=int(52*rnd(1)+1)
            alreadyfound=0
            rem  =============================================================
            rem    Check if a number is already found and if yes, generate
            rem    another
            rem  =============================================================
            for j=1 to nextnumber
                if randomseries(j)=x then alreadyfound=1
                if randomseries(j)=x then exit for
            next j
        loop until alreadyfound=0
            randomseries(nextnumber)=x
    next nextnumber

    for k=1 to 52
        if k=27 then print
        if randomseries(k)<10 then print "0";
        print randomseries(k);" ";
    next k
 
User IP Logged

LANG MEY YER LUM REEK

Life is a coin. You can spend it any way you wish but you can spend it only once
Welopez
Moderator
ImageImageImageImageImage


member is offline

Avatar

Never let your beliefs get in the way of learning.


PM

Gender: Male
Posts: 4407
xx Re: SHUFFLING (Cards, Questions, Images)
« Reply #8 on: Mar 2nd, 2012, 5:53pm »

Very good, Gearce! It works, without confusion, and what more would you expect from a well written routine?

The beauty of this forum is that we can share new ideas and techniques, with all members. We can also ask a question if we should get stumped. I think I've asked two in the 8 years I've been here, but they weren't on the same day. LOL!

We usually get more than one answer, allowing us to choose the one easiest for us to follow. That was what caught my attention using a two-dimension shuffle to sort cards according to a "random number tag." In fact, they don't have to be cards, they can be paths to display images, music to be played next, or flowers to decorate a room.

As I always say, "Knowledge gains no interest when locked in a vault, but could lead to unlocking the universe if shared."

Welcome to Just Basic, Gearce. Keep sharing! smiley
User IP Logged

JB 1.01
Win7 64bit, 4 GB RAM, Pentium 6200@2.13 GHz (laptop)
WinXP, 1 GB RAM, Intel N270@1.6 GHz (netbook)
cassiope01
Senior Member
ImageImageImageImageImage


member is offline

Avatar




PM

Gender: Male
Posts: 669
xx Re: SHUFFLING (Cards, Questions, Images)
« Reply #9 on: Mar 3rd, 2012, 12:01am »

or the same thing with INSTR() :

Code:
rem  =========================================================================
rem    Initialise counters
rem  =========================================================================
    cardpack=52

rem  =========================================================================
rem     Declare array/s
rem  =========================================================================
    dim randomseries(cardpack)

rem  =========================================================================
rem    Shuffle cards and write results to screen
rem  =========================================================================
    for nextnumber=1  to cardpack
        do
            x=int(52*rnd(1)+1)
            'alreadyfound=0
            n$ = right$(100+x,2)
            rem  =============================================================
            rem    Check if a number is already found and if yes, generate
            rem    another
            rem  =============================================================
           ' for j=1 to nextnumber
           '     if randomseries(j)=x then alreadyfound=1
           '     if randomseries(j)=x then exit for
           ' next j
        loop until instr(nr$,n$)=0 'alreadyfound=0
        nr$ = nr$ + n$ + " "
        randomseries(nextnumber)=x
    next nextnumber

    for k=1 to 52
        if k=27 then print
        if randomseries(k)<10 then print "0";
        print randomseries(k);" ";
    next k 


;) :D
User IP Logged

"It is better to mobilize its intelligence for stupid things, rather than mobilizing its stupidity for intelligent things."
Gearce
Full Member
ImageImageImageImage


member is offline

Avatar




PM

Gender: Male
Posts: 153
xx Re: SHUFFLING (Cards, Questions, Images)
« Reply #10 on: Mar 3rd, 2012, 01:49am »

Thanks Welopez and cassiope01 for your replies.

Welopez, I understand the subject of the shuffle is not limited to cards. It's just that a lot of my programmes in the Dark Basic language involved cards, hence the choice.

cassiope01, I have a lot of familiarising to do since I have just joined the Just Basic membership. You say 'or the same thing with INSTR()'. The following is a print out of a run using your programme and a few of the numbers are duplicated - those which I have underlined, so it wouldn't be of use in a programme requiring a series of numbers with no repeats.
28 27 20 24 51 26 25 14 09 46 16 43 46 43 26 42 52 37 10 47 47 40 05 47 51 43
16 13 30 21 32 11 11 23 03 05 02 09 13 09 47 37 13 17 15 09 36 51 42 43 26 41
« Last Edit: Mar 3rd, 2012, 01:56am by Gearce » User IP Logged

LANG MEY YER LUM REEK

Life is a coin. You can spend it any way you wish but you can spend it only once
cassiope01
Senior Member
ImageImageImageImageImage


member is offline

Avatar




PM

Gender: Male
Posts: 669
xx Re: SHUFFLING (Cards, Questions, Images)
« Reply #11 on: Mar 3rd, 2012, 02:12am »

Oops ! sorry, it's better like that...

Code:
rem  =========================================================================
rem    Initialise counters
rem  =========================================================================
    cardpack=52

rem  =========================================================================
rem     Declare array/s
rem  =========================================================================
    dim randomseries(cardpack)

rem  =========================================================================
rem    Shuffle cards and write results to screen
rem  =========================================================================
    for nextnumber=1  to cardpack
        rem  =============================================================
        rem    Check if a number is already found and if yes, generate
        rem    another
        rem  =============================================================
        do
            x=int(52*rnd(1)+1)
            n$ = ".";x;"."
        loop until instr(nr$,n$)=0
        nr$ = nr$ + n$
        randomseries(nextnumber)=x
    next nextnumber

    for k=1 to 52
        if k=27 then print
        if randomseries(k)<10 then print "0";
        print randomseries(k);" ";
    next k 
« Last Edit: Mar 3rd, 2012, 02:15am by cassiope01 » User IP Logged

"It is better to mobilize its intelligence for stupid things, rather than mobilizing its stupidity for intelligent things."
tsh73
JB-Supporter


member is offline

Avatar




PM

Gender: Male
Posts: 3636
xx Re: SHUFFLING (Cards, Questions, Images)
« Reply #12 on: Mar 3rd, 2012, 2:05pm »

You probably know (and you really should know),
that shuffling by
"Let's keep tossing a coin until we get card what was not chosen before"
is INEFFICIENT.
It's so obviously inefficient it makes my brain hurt.

(just for a record, I gave link to better way in Reply #4, a year ago).
User IP Logged

Q: "And if I took your codes and compile them, and sell them for a profit"?
A: Go ahead. I had my share of good then I coded it for fun, if you can make better use of it - please do.
(enjoying JB 1.01 on WinXP, netbook and desktop)
KcDan
Full Member
ImageImageImageImage


member is offline

Avatar




Homepage PM


Posts: 439
xx Re: SHUFFLING (Cards, Questions, Images)
« Reply #13 on: Mar 4th, 2012, 10:40am »

Ill throw in my card fxns too then.

Code:
global CardPointer
dim CardDeck(51)
dim CardRanks$(12)
dim CardSuits$(3)

CardSuits$(0)="Spades":CardSuits$(1)="Hearts":CardSuits$(2)="Diamonds":CardSuits$(3)="Clubs"
CardRanks$(0)="Ace":CardRanks$(1)="Two":CardRanks$(2)="Three":CardRanks$(3)="Four"
CardRanks$(4)="Five":CardRanks$(5)="Six":CardRanks$(6)="Seven":CardRanks$(7)="Eight"
CardRanks$(8)="Nine":CardRanks$(9)="Ten":CardRanks$(10)="Jack":CardRanks$(11)="Queen"
CardRanks$(12)="King"



call BuildDeck
call ShuffleDeck

for i = 1 to 52
    card=DrawCard()
    print i;": ";CardRanks$(GetRank(card));" of ";CardSuits$(GetSuit(card))
next i

end


sub BuildDeck
    for s=0 to 3
        for r=0 to 12
            CardDeck(s*13+r)=MakeCard(s,r)
        next r
    next s
end sub

sub ShuffleDeck
    CardPointer=0
    for i = 0 to 51
        cardTo=int(rnd(1)*52)
        card=CardDeck(cardTo)
        CardDeck(cardTo)=CardDeck(i)
        CardDeck(i)=card
    next i
end sub

function DrawCard()
    DrawCard=CardDeck(CardPointer)
    CardPointer=CardPointer+1
end function

function MakeCard(suit,rank)
    MakeCard=rank*4 or suit
end function

function GetSuit(card)
    GetSuit=card and 3
end function

function GetRank(card)
    GetRank=(card and 60)/4
end function
 
User IP Logged

http://ZPtr.net/

My Site
http://KcDan.com/
Gearce
Full Member
ImageImageImageImage


member is offline

Avatar




PM

Gender: Male
Posts: 153
xx Re: SHUFFLING (Cards, Questions, Images)
« Reply #14 on: May 13th, 2012, 8:48pm »

Sorry to bump up this thread again but I think this is an interesting little 'cards shuffler". It is from a programme, Visual Blackjack, designed and written by James Dobb aka SemiSkim at http://jbfilesarchive.com/phpBB3/viewtopic.php?f=4&t=903.

Code:
' CARDS SHUFFLER

dim CARD(52),USED(52)
do
        CARDS = CARDS + 1
        [BK1]
        CARD(CARDS) = INT(RND(1)*52) + 1
        IF USED(CARD(CARDS)) = 1 THEN GOTO [BK1]
        USED(CARD(CARDS)) = 1
loop while CARDS<52
 

Run this to test it.

Code:
' CARDS SHUFFLER

dim CARD(52),USED(52)
do
        CARDS = CARDS + 1
        [BK1]
        CARD(CARDS) = INT(RND(1)*52) + 1
        IF USED(CARD(CARDS)) = 1 THEN GOTO [BK1]
        USED(CARD(CARDS)) = 1
        select case CARDS
            case 14,27,40:print
        end select
        print using("###",CARD(CARDS));
loop while CARDS<52
 
« Last Edit: May 13th, 2012, 8:49pm by Gearce » User IP Logged

LANG MEY YER LUM REEK

Life is a coin. You can spend it any way you wish but you can spend it only once
Pages: 1 2 3  Notify Send Topic Print
« Previous Topic | Next Topic »

Conforums Terms of Service | Membership Rules | Home | Search | Recent Posts | Notification | Format Your Message | Installation FAQ

Donate $6.99 for 50,000 Ad-Free Pageviews!

| |

This forum powered for FREE by Conforums ©
Sign up for your own Free Message Board today!
Terms of Service | Privacy Policy | Conforums Support | Parental Controls