Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW

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.)


Log In?

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

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (3)
As of 2016-10-01 23:35 GMT
Find Nodes?
    Voting Booth?
    How many different varieties (color, size, etc) of socks do you have in your sock drawer?

    Results (9 votes). Check out past polls.