Choose unique random number from an array

2019-08-05 12:33发布

问题:

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



标签: ruby random