Thursday, 5 September 2013

Select random unique element from an array

Select random unique element from an array

This question goes over how to select random elements from an array using
sample, but I'd like to do this multiple times, selecting a unique one
each time.
The simplest solution I can think of is something like this, but I feel
like there must be a simpler way (without modifying the original array):
myArray = ["stuff", "widget", "ruby", "goodies", "java", "emerald", "etc" ]
selected = []
first = myArray.sample
selected << first
first = second
while(first == second) do
second = myArray.sample
end
selected << second

No comments:

Post a Comment