From: Rick DeNatale Date: 2008-07-04T02:41:47+09:00 Subject: Re: pseudo-randomize an array in a consistent order ------=_Part_810_1372816.1215107093518 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit Content-Disposition: inline On Thu, Jul 3, 2008 at 12:59 PM, Max Williams wrote: > ThoML wrote: > > On Jul 3, 4:56 pm, Max Williams wrote: > >> Does anyone know how to pseudo-randomize an array (eg with a seed) so > >> that you get the same order every time you do it? > > > > ruby19 has a Array#shuffle method: > > irb(main):001:0> Kernel.srand(1); [1,2,3,4,5].shuffle > > => [2, 4, 1, 5, 3] > > irb(main):002:0> Kernel.srand(1); [1,2,3,4,5].shuffle > > => [2, 4, 1, 5, 3] > > I'm only on 1.8.6 (and not likely to change soon since we'd want to do > all our work servers as well), but out of interest, do you know how > shuffle compares to .sort_by{rand} (thanks rob!) in terms of efficiency? It looks like it should be faster for larger arrays. There are actually two methods Array#shuffle! and Array#shuffle Here's a Ruby translation of the C code: class Array def shuffle! i = length - 1 while (i > 0) j = rand(i) # Swap self[i] and self[j] # This might be more elegant using a parallel assignment, but # parallel assignment generates a temporary array, so this is # a little closer to the C code tmp = self[i] self[i] = self[j] self[j] = self[i] i -= 1 end self end def shuffle self.dup.shuffle! end end So shuffle is O(n) whereas any sort is going to be O(>n) -- Rick DeNatale My blog on Ruby http://talklikeaduck.denhaven2.com/ ------=_Part_810_1372816.1215107093518--