Tuesday, May 12, 2009

Randomizing an Array

This article deals about ruby array randomize.Some of the piece of code available are taken from web.If we want to scramble an array into a random order, then we want to use the rand in the kernel module

Ruby array randomize


By slice & rand


class Array
def random
a=self.dup
result=[]
self.length.times do
result << a.slice!(rand(a.length))
end
return result
end
end
x=1,2,3,4,5
=> [1, 2, 3, 4, 5]
irb(main):107:0> x.random
=> [1, 4, 5, 2, 3]
irb(main):108:0> x.random
=> [1, 4, 3, 5, 2]
irb(main):109:0> x.random
=> [4, 2, 3, 1, 5]

By Sort_by & rand

randomize=(1..10).to_a.sort_by{rand}=> [1, 4, 6, 2, 5, 3]
irb(main):262:0> x.sort_by{rand}
=> [4, 5, 3, 1, 6, 2]
irb(main):263:0> x.sort_by{rand}
=> [3, 1, 6, 2, 4, 5]
irb(main):264:0> x.sort_by{rand}
=> [2, 1, 6, 3, 5, 4]

1 comment:

  1. More on Ruby randomness here:

    http://snippets.dzone.com/posts/show/4697

    ReplyDelete