Randomly picking unique elements

Viewed 46

I use rand to reach random three element from a and add this m values to array but I want them to be unique. So, array can't be like this: array = [1,1,2]. How can I check when two elements are equal and how to prevent this other than sample method? I was thinking about this: Let's assume m=1 when times method runs the first time. If m =1 at the second time, I want to skip this value and reach a different one. Is there any code explanation for this ? Or maybe more different way?

a = [1, 2, 3, 4]
array = []

3.times do 
  m = a[rand(a.size)]
  array << m 
end
2 Answers

Use shuffle and slice 3 elements:

a = [1, 2, 3, 4]
shuffled = a.shuffle[0..2]

As I understand you wish to write a method similar to Array#sample, that returns a pseudo-random sample of a given size without replacement. I suggest the following, which I believe would be relatively efficient, particularly when the sample size is small or large relative to the size of array.

def sample(arr, sample_size)
  n = arr.size
  raise ArgumentError if n < sample_size
  a = arr.dup
  m = (sample_size < n/2) ? sample_size : n - sample_size      
  m.times do
    i = rand(n)
    n -= 1
    a[i], a[n] = a[n], a[i]
  end
  n = arr.size
  (sample_size < n/2) ? a[n-sample_size..] : a[0, sample_size]
end
a = [7, 5, 7, 1, 9, 6, 2, 0, 6, 7]  

Notice that if sample_size >= arr.size/2 I sample arr.size - sample_size elements and return the unsampled elements.

Related