From: Matt Chen Date: 2007-02-26T01:59:50+09:00 Subject: Re: extract a random number of items from an array ------=_Part_49673_16569431.1172422787518 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Content-Disposition: inline Here is my solution, it should be work. ---- def extract_values(array, n) len = array.length (len - 1).downto(len - n) do |i| sway_index = rand(len) % i array[i], array[sway_index] = array[sway_index], array[i] end return array[len-n..len-1] end On 2/26/07, James Edward Gray II wrote: > > On Feb 25, 2007, at 10:20 AM, Josselin wrote: > > > given an array of values, how should I extract an random number of > > these values > > > > a = [13, 15, 17, 18, 19, 20, 21, 23, 24, 25, 26, 27, 28, 29, 30, > > 31, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, > > 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, > > 74, 75, 76, 77, 78, 79, 81, 82, 83, 84, 85, 86, 88, 89, 90, 91, 92, > > 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106] > > Just give a random chance that a value is added to the result set: > > >> a.select { rand(2).zero? } > => [13, 15, 23, 24, 25, 26, 27, 28, 29, 31, 41, 42, 44, 45, 46, 47, > 49, 51, 52, 53, 55, 58, 60, 61, 62, 66, 67, 68, 69, 70, 71, 72, 73, > 75, 76, 78, 81, 82, 83, 89, 90, 91, 94, 95, 98, 99, 100, 101, 103, > 104, 105, 106] > >> a.select { rand(2).zero? } > => [13, 18, 19, 20, 21, 24, 26, 27, 28, 29, 30, 31, 41, 42, 44, 48, > 49, 51, 52, 53, 55, 57, 58, 59, 62, 63, 64, 66, 68, 70, 79, 81, 82, > 83, 86, 89, 90, 91, 92, 94, 97, 98, 102, 104, 105, 106] > >> a.select { rand(2).zero? } > => [15, 17, 18, 19, 20, 21, 23, 25, 30, 41, 44, 45, 46, 49, 50, 51, > 52, 53, 54, 57, 59, 63, 64, 66, 68, 70, 72, 73, 76, 78, 79, 81, 82, > 90, 91, 95, 97, 101, 102, 104] > > Hope that helps. > > James Edward Gray II > > ------=_Part_49673_16569431.1172422787518--