Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
Random numbers - the most efficient way
Message
De
08/09/2004 13:02:22
 
 
À
07/09/2004 23:39:16
Information générale
Forum:
Visual FoxPro
Catégorie:
Codage, syntaxe et commandes
Divers
Thread ID:
00939849
Message ID:
00940342
Vues:
37
>>>>Mohammed Qasem gave me a quite interesting problem, which I am now (12:13am) trying to solve the most elegant way.
>>>>
>>>>Here is a problem:
>>>>
>>>>We have a small set of records. We need to extract randomly smaller subset of records. Say, we have 300 records, we would need to randomly choose 40 records out of this set. Number of records to remove is always less than the number of records in a set.
>>>
>>>The way I used to do this before "select top n" was available, was to use an array with record numbers, select one element at random, remove it from array (using adel() and redimensioning the array).
>>
>>No need to redimension if you take the last avaialable entry and swap it with your currently selected "random" number. Used this for a card shuffle routine, no repeats.
>>
>>
DIMENSION aCards[52]
>>FOR x=1 TO 52
>>  aCards[x] = x
>>ENDFOR
>>RAND(0)
>>FOR x=52 TO 1 STEP -1
>>  nRnd = INT(RAND()*x) + 1
>>  nMax = aCards[x]
>>  ? aCards[nRnd]
>>  aCards[nRnd] = nMax
>>ENDFOR
Hi Fred,
>
>I'm not sure this routine is reliable in the general case. For example, it should work if, say, RAND() always returned 0.5. If I modify it as follows (using only 5 cards for illustration):
DIMENSION aCards[5]
>FOR x=1 TO 5
>  aCards[x] = x
>ENDFOR
>RAND(0)
>FOR x=5 TO 1 STEP -1
>  nRnd = INT(0.5*x) + 1
>  nMax = aCards[x]
>  ? aCards[nRnd]
>  aCards[nRnd] = nMax
>ENDFOR
>
>* 5 array values are 1, 4, 4, 4, 5
I've never seen it fail in 1000's (probably many more) iterations in the card applications. I've also used the same algorithm to randomly display pixels in an image, and have never left any non-displayed portions.

As a matter of fact, I just ran a pass of 10000 passes on your data with your above code (hardcode .5) and it did not fail. Why would that be?
Fred
Microsoft Visual FoxPro MVP

foxcentral.net
Précédent
Répondre
Fil
Voir

Click here to load this message in the networking platform