Choose unique random number from an array

孤者浪人 提交于 2020-01-06 03:15:34

问题


b is the maximum winner that I want.

b.times do
  winner = participant[rand(participant.count)]
end

I need to generate a unique winner every time. How can I achieve this without making too many changes to this code?


回答1:


There is already a method for that. Just use Array#sample:

winners = participants.sample(b)



回答2:


You can use Array#delete_at which deletes an item at specified index and returns the deleted item. We can now ensure that item once picked as winner will never be picked again

# sample data
participant = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
b = 3

# preserve the original array
p = participant.dup 

# pick winner
b.times do
    winner = p.delete_at(rand(participant.count))
end

You can use Array#sample (as ndn suggested) if your program is okay to get all winners in one shot



来源:https://stackoverflow.com/questions/32562502/choose-unique-random-number-from-an-array

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