Choose unique random number from an array

2019-08-05 11:50发布

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?

标签: ruby random
2条回答
ゆ 、 Hurt°
2楼-- · 2019-08-05 12:32

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

winners = participants.sample(b)
查看更多
Luminary・发光体
3楼-- · 2019-08-05 12:44

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

查看更多
登录 后发表回答