Randomizing array elements

瘦欲@ 提交于 2020-01-02 02:01:06

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!