nirmal
nirmal

Reputation: 1121

Randomizing array elements

I have an array @number = [1,2,3,4,5,6,7,8,9]
Now, I want to randomize the array content... something like eg: [5,3,2,6,7,1,8]
Please guide me how to proceed with it.

Upvotes: 8

Views: 4116

Answers (5)

Dhanu
Dhanu

Reputation: 69

[1,2,3,4,5,6,7,8,9].sort_by {rand}[0,9]  
=> [5, 7, 3, 8, 9, 4, 2, 1, 6]

Upvotes: 1

Avinasha Shastry
Avinasha Shastry

Reputation: 822

If you are using old version of ruby... this will work

def randomize(array)
b = []
array.length.downto(1) { |n|
    b.push array.delete_at(rand(n))
} 
b 

end

a = [1,2,3,4,5] b=randomize(a) print b

Upvotes: -1

Nikolaus Gradwohl
Nikolaus Gradwohl

Reputation: 20124

the shuffle command returns a randomized version of an array

eg:

[1,2,3].shuffle => [2,3,1]

Upvotes: 8

Dave Pirotte
Dave Pirotte

Reputation: 3816

Use the shuffle method ...

irb(main):001:0> [1,2,3,4,5].shuffle
=> [3, 4, 2, 5, 1]

Upvotes: 13

RyanHennig
RyanHennig

Reputation: 1072

loop n times
   i = random array index
   j = random array index
   swap elements i and j
end

Upvotes: -2

Related Questions