From: jzakiya Date: 2007-02-26T12:00:06+09:00 Subject: Re: extract a random number of items from an array On Feb 25, 4:50 pm, Brian Candler wrote: > On Mon, Feb 26, 2007 at 06:40:05AM +0900, Josselin wrote: > > >Are you trying to do pick 'n' elements from 'a' like lottery balls? i.e. > > >once a value has been picked once, it cannot be picked again? > > no, I need to put all the balls again for the next pick > > Still not entirely clear, but I think one of these is what you mean: > > Option 1: After picking one ball, you put that one ball back, then pick > another ball, put it back etc. You repeat this 'n' times to get your > selection of 'n' balls. > > result = [] > n.times { result << a[ rand(a.size) ] } > > Clearly this allows for duplicates. > > Option 2: You pick 'n' balls out of the bag (without replacement). Then you > put these balls back in, so that on the next run you pick another 'n' balls > from the original set. > > b = a.dup > result = [] > n.times { result << b.slice!( rand(b.size) ) } > > You don't get any duplicates within your selection of 'n' balls, but the > fact that you've picked a ball on one run doesn't prevent it from being > picked on a subsequent run. > > Regards, > > Brian. But for n > a.size Option 1 fills result with valid values while for Option 2 it fills it with nil. Problem didn't state that n always <= a.size.