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?
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?
There is already a method for that. Just use Array#sample
:
winners = participants.sample(b)
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