Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: Selecting array records - code question

by dash2 (Hermit)
on Jun 10, 2003 at 00:17 UTC ( #264498=note: print w/ replies, xml ) Need Help??


in reply to Selecting array records - code question

Seems a little weird to me. Suppose you have 8 elements, so $n is about 2 and $m is 8. The first element of sub has a 2 in 8 chance of being selected. If it is selected, $n is now 1 and $m is 7, so the next element has a 1 in 7 chance of being selected. If it isn't selected, the next element has a 2 in 7 chance of being selected. In other words, you are going to get the right number of elements returned, but not all elements have an equal chance of being returned.

(Or am I being stupid?)

I suggest that your third line could be:

while (@selected < $n) { push @selected, splice(@sub, int rand @sub, 1); }

which should ensure an even distribution, is more readable, and only iterates $n times rather than through the whole @sub array. (Copy @sub if you need to preserve the original.)

andramoiennepemousapolutropon


Comment on Re: Selecting array records - code question
Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://264498]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (6)
As of 2014-12-19 04:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (70 votes), past polls