Question

I know that ruby has myarray.sample(i) to sample i elements from an array. My problem is that the number of elements are not integers.

i.e I would like a method mysample such that if I call myarray.mysample(1.5) 10 times, the number of elements I get should be close to 15.

With sample, I will get either 10 or 20 depending on the int conversion. Similarly, if I call myarray.mysample(.25) I want it to return an element with 0.25 probability (that is, it should return one element one times out of four, and three times out of four, it should return an empty array/nil).

How do I do this?

My attempt so far:

def mysample(array,s)
  ints = array.sample(s.floor)
  if (Random.rand > s - s.floor)
    ints << array.sample
  end
  return ints
end

Is there a better way?

Was it helpful?

Solution

Basing my answer off of this:

if I call myarray.mysample(1.5) 10 times, the number of elements I get should be close to 15.

Extending Array yields the following:

class Array
    def mysample(num)
       self.sample( ( num + rand() ).floor )
    end
end

> [1, 2, 3, 4, 5].mysample(2.5)
=> [1, 3]

> [1, 2, 3, 4, 5].mysample(2.5)
=> [4, 2, 5]

> [1, 2, 3, 4, 5].mysample(0.5)
=> []

> [1, 2, 3, 4, 5].mysample(0.5)
=> [3]

etc.

OTHER TIPS

To optimal argument is there to decide the spread of randomness for numbers above 1.

class Array
  def my_sample(number, deviation=0.3)
    if number < 1
        return sample rand(100) < number * 100 ? 1 : 0
    end
    speard = (number*deviation).to_i
    randomness = rand(-speard..speard)
    sample(number+randomness)
  end
end

p [1,2,3,4,5,6,7,8,9,10].my_sample(0.5) #=> []
p [1,2,3,4,5,6,7,8,9,10].my_sample(0.5) #=> [3]

p [1,2,3,4,5,6,7,8,9,10].my_sample(5) #=> [9, 2, 1, 4, 10, 7, 3]
p [1,2,3,4,5,6,7,8,9,10].my_sample(5) #=> [7, 2, 3, 8]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top