When you think ASP, think...
Recent Articles
All Articles
ASP.NET Articles
ASPFAQs.com
Message Board
Related Web Technologies
User Tips!
Coding Tips

Sections:
Sample Chapters
Commonly Asked Message Board Questions
JavaScript Tutorials
MSDN Communities Hub
Official Docs
Security
Stump the SQL Guru!
XML Info
Information:
Feedback
Author an Article
ASP ASP.NET ASP FAQs Message Board Feedback

The 4 Guys Present: ASPFAQs.com

Jump to a FAQ
Enter FAQ #:
..or see our 10 Most Viewed FAQs.

4GuysFromRolla.com : ASP FAQS : Math Functions


Question:

How can I shuffle a deck of cards or similar set of sequential numbers? How can I reorder a list of things in random order?


[Print this FAQ]

Answer: Think about one way you could do this with a physical deck of cards.

You could put the cards in order (not necessary, but in theory it shouldn't matter). Then you could randomly pick any card from the ones in the deck and either turn it over (to display it immediately) or move it to a second pile (to create a shuffled deck).

If you were really good about picking one card from the remaining ones in a truly random manner, the resulting output (display or deck) would be in truly random order.

Essentially, that's what we will do in the code that is given below.

The only hard part is replicating the physical removal of the card from the deck, so that the deck gets smaller and smaller. We could simply do this using an array and "sliding" all the cards "above" the chosen one "down" by one notch. This works. But it can be *very* slow!

So let's think of a slight modification of that physical scheme: Instead of just picking a random card from the deck, let's pull out the chosen card and--at the same time--take the card on the top of the deck and shove it there in place of the picked card. Does that change anything, really? Of course not! With good picking of random numbers, you get good random results.

And so, on to the code:

<%
' This function will DEAL the "needed"
' number of values from the given "inArray"
'
' If the value for "needed" matches the
' upper bound of the "inArray", then the
' entire "inArray" is dealt out.
'
' NOTE: As written, this code never uses
' or touches element zero of the inArray
' and puts no value in element zero of the
' outArray. (Obviously, easy to change.)
'
Function Shuffle( inArray, needed )
    ' find out how many input elements there are...
    incnt = UBound( inArray )
    ' then create the output array to be the size
    ' requested via the "needed" argument
    dim outArray
    redim outArray( needed )

    ' now we will select the number of values
    ' specified as "needed"...
    For i = 1 To needed
        ' choose a random number from 1 to our
        ' current input array usage size...
        choose = Int( incnt * Rnd(1) ) + 1

        ' put that chosen element into the next
        ' slot in the output array...
        outArray( i ) = inArray( choose )
        
        ' here's the tricky part: Since we just
        ' used the "choose" element, we don't need
        ' it any more...we replace it with the last
        ' element of the in-use part of the array!
        inArray( choose ) = inArray( incnt )
        
        ' and then we (effectively) shrink the array!
        ' Next time through the loop, there will be
        ' one fewer elements in the array to choose
        ' from...because we have (effectively) deleted
        ' the one just chosen!
        incnt = incnt - 1

    Next
    ' return the shuffled output
    Shuffle = outArray
End Function

' This is just a convenience function
'
' If you need *all* the "cards" in a deck of a given
' size shuffled, and the "name" of a card can just be
' its numeric position in the unshuffled deck, then
' just call ShuffleDeck, passing the size of the deck
' to be shuffled.
'
Function ShuffleDeck( deckSize )
    Dim i, deck()
    ReDim deck( deckSize )
    For i = 1 To deckSize
        deck(i) = i
    Next
    ShuffleDeck = Shuffle( deck, deckSize )
End Function    
%>

<HTML><BODY>

<%
Randomize

ar = Array(0,"you","can","put","anything","in","the","array","of","course")
str = Mid( Join(ar," "), 2 )
Response.Write "Picking 4 words from this list: <STRONG>" _
             & str & "</STRONG><OL>" & vbNewLine
sh = Shuffle( ar, 4 )
For i = 1 to 4
    Response.Write "<LI>" & sh(i) & vbNewLine
Next

Response.Write "</OL><P> <P>" & vbNewLine

Response.Write "Shuffling a 'deck' of 20 numbered cards.<BR>" _
            & "The cards were originally numbered from 1 to 20.<P>" & vbNewLine
sh = ShuffleDeck( 20 )
str = Mid( Join( sh, "," ), 2 )
Response.Write "The shuffled deck: <STRONG>" & str & "</STRONG>" & vbNewLine
%>

</BODY></HTML>


I have included a pair of demonstrations of the code. First, by picking four words from a list (array) of words. Second, I use the "auxiliary" function that I show there to generate and shuffle a "deck" of 20 cards.

Please do try these on your own machine(s)! Then adapt the functions as you will for your own purposes.

Happy programming!



FAQ posted by Bill Wilkinson at 1/17/2001 9:44:20 PM to the Math Functions category. This FAQ has been viewed 46,259 times.

Do you have a FAQ you'd like to suggest? Suggestions? Comments? If so, send it in! Also, if you'd like to be a FAQ Admin (creating/editing FAQs), let me know! If you are looking for other FAQs, be sure to check out the 4Guys FAQ and Commonly Asked Messageboard Questions!

Most Viewed FAQs:

1.) How can I format numbers and date/times using ASP.NET? For example, I want to format a number as a currency. (761643 views)
2.) I am using Access and getting a 80004005 error (or a [Microsoft][ODBC Microsoft Access Driver] The Microsoft Jet database engine cannot open the file '(unknown)' error) when trying to open a connection! How can I fix this problem? (207777 views)
3.) How can I convert a Recordset into an array? Also, how can I convert an array into a Recordset? (202549 views)
4.) How can I quickly sort a VBScript array? (196039 views)
5.) How can I find out if a record already exists in a database? If it doesn't, I want to add it. (156019 views)
6.) How do I display data on a web page using arrays instead of Do...While...MoveNext...???... (152331 views)
7.) When I get a list of all files in a directory via the FileSystemObject, they aren't ordered in any reasonable way. How can I sort the files by name? Or by size? Or by date created? Or... (140381 views)
8.) For session variables to work, must the Web visitor have cookies enabled? (110162 views)
9.) Can I send emails without using CDONTS? (107083 views)
10.) How can I take the result of a SELECT...MULTIPLE or a group of same-named checkboxes and turn it into a query? That is, if the user selects 3 answers, how can I construct a query that looks for all 3? (106308 views)
Last computed at 9/17/2007 3:22:00 AM


ASP.NET [1.x] [2.0] | ASPMessageboard.com | ASPFAQs.com | Advertise | Feedback | Author an Article