From: Pierre-Charles David Date: 2001-10-09T17:49:31+09:00 Subject: [ruby-talk:22288] Re: [Newbie] Switching from Perl : suffling Niklas Frykholm wrote: > On Tue, Oct 09, 2001 at 04:58:24AM +0900, Dave Thomas wrote: > >>How about something like >> >> class Array >> def shuffle >> each_index {|i| o = rand(size); self[i], self[o] = self[o], self[i] } >> end >> end >> One of my teachers once showed me this method, which I find quite elegant (although perhaps not very efficient because of the arrays creation, but still O(n) ): module Enumerable def shuffle # Associate a random number to each element pairs = self.collect { |item| [rand(), item] } # Sort the pairs according to the random part # and extract the original data (pairs.sort { |x, y| x[0] <=> y[0] }).collect { |pair| pair[1] } end end srand a = (1..20).to_a p a, a.shuffle -- Pierre-Charles David (pcdavid emn fr) Computer Science PhD Student, �cole des Mines de Nantes, France Homepage: http://purl.org/net/home/pcdavid