[Gambas-user] A few algorithms #1

Bruce bbruen at ...2308...
Thu Jan 10 12:56:31 CET 2013


This may be of interest to some so I post it with best interests.

Problem: Given a list of items shuffle them into a random order, e.g,
cards, cars, boyfriends, girlfriends, recipes, whatever.
Answer: For small data sets:

        '' <p>Fisher-Yates shuffle routine to randomise source lists. 
        '' Returns a reasonably* random re-ordering of the list in O(log
        n)
        '' time.</p>
        '' <i><p>* "reasonably? It has a slight bias to the left of the
        '' original list. If "n" is small, say n<~100, then the bias is
        '' irrelevant, but is "n" is large then the bias creeps
        in.</p></i>
        '' More information on the Fisher-Yates shuffle at wikipedia is
        '' available <a
        href="http://en.wikipedia.org/wiki/Fisher-Yates_shuffle">here</a></p>
        Private/Public Function Shuffle(list As Variant[]) As Variant[] 
        
          Dim iLast As Integer
          Dim iRnd As Integer
        
          iLast = list.Max
          Randomize
          While iLast > 1
            iRnd = Rnd(0, iLast)
            Swap list[iLast], list[iRnd]
            Dec iLast
          Wend
        
          Return list
        
        End 

As I haven't said, today the doctor gave me a probability of either 3
months or 30 years.  So, given my luck, I'd better start getting some of
this stuff out there.

brta
Bruce 





More information about the User mailing list