Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
294 views
in Technique[技术] by (71.8m points)

arrays - Randomly picking unique elements

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...