问题
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.
回答1:
Use the shuffle method ...
irb(main):001:0> [1,2,3,4,5].shuffle
=> [3, 4, 2, 5, 1]
回答2:
the shuffle command returns a randomized version of an array
eg:
[1,2,3].shuffle => [2,3,1]
回答3:
[1,2,3,4,5,6,7,8,9].sort_by {rand}[0,9]
=> [5, 7, 3, 8, 9, 4, 2, 1, 6]
回答4:
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
回答5:
loop n times
i = random array index
j = random array index
swap elements i and j
end
来源:https://stackoverflow.com/questions/3818762/randomizing-array-elements