Revision: 12009
Initial Code
Initial URL
Initial Description
Initial Title
Initial Tags
Initial Language
at February 26, 2009 21:29 by Shurik76
Initial 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
%>
Initial URL
http://www.aspfaqs.com/aspfaqs/ShowFAQ.asp?FAQID=114
Initial Description
Initial Title
Array Shuffle (w. downsize)
Initial Tags
Initial Language
ASP