Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 如何从数组中选取分数样本?_Ruby_Arrays_Sample - Fatal编程技术网

Ruby 如何从数组中选取分数样本?

Ruby 如何从数组中选取分数样本?,ruby,arrays,sample,Ruby,Arrays,Sample,我知道ruby有myarray.sample(I)从数组中抽取I元素。我的问题是元素的数量不是整数 i、 e我想要一个方法mysample,这样如果我调用myarray.mysample(1.5)10次,我得到的元素数应该接近15 使用sample,根据int转换,我将得到10或20。类似地,如果我调用myarray.mysample(.25)我希望它以0.25的概率返回一个元素(即,它应该四次返回一个元素,四次返回三次,它应该返回一个空数组/nil) 我该怎么做 我迄今为止的努力: def m

我知道ruby有
myarray.sample(I)
从数组中抽取
I
元素。我的问题是元素的数量不是整数

i、 e我想要一个方法
mysample
,这样如果我调用
myarray.mysample(1.5)
10次,我得到的元素数应该接近15

使用
sample
,根据int转换,我将得到10或20。类似地,如果我调用
myarray.mysample(.25)
我希望它以
0.25
的概率返回一个元素(即,它应该四次返回一个元素,四次返回三次,它应该返回一个空数组/nil)

我该怎么做

我迄今为止的努力:

def mysample(array,s)
  ints = array.sample(s.floor)
  if (Random.rand > s - s.floor)
    ints << array.sample
  end
  return ints
end
def mysample(数组,s)
ints=数组。示例(s.floor)
如果(Random.rand>s-s.floor)

ints我的回答基于以下内容:

如果我调用
myarray.mysample(1.5)
10次,得到的元素数应该接近15个

扩展
数组
会产生以下结果:

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.

对于最优参数来说,它决定了大于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]
类数组
def my_样本(数量,偏差=0.3)
如果数字<1
返回样本兰特(100)
p[1,2,3,4,5,6,7,8,9,10].我的样本(0.5)#=>[3]
p[1,2,3,4,5,6,7,8,9,10].my_样本(5)#=>[9,2,1,4,10,7,3]
p[1,2,3,4,5,6,7,8,9,10].我的样本(5)#=>[7,2,3,8]

什么是“元素的数量不是整数”?如果你有一个数组,例如,有100个元素,你能进一步解释一下“选择概率为0.25的元素”是什么意思吗?我知道选择给定元素的概率为0.25意味着什么,但不确定你的例子是什么意思。在我的例子中,它应该在四次中返回三次空,并且在四次中返回一次随机元素。@sawa删除了该语句,并重新编写了。我明白你的要求。谢谢你的解释。是否存在任何其他约束,例如调用
my\u array.sample(r)
时返回的元素数是否不应超过
ceil(r)
?或者返回的元素数是否应始终介于
floor(r)
ceil(r)
之间?@ZachKemp我已根据您的要求进行了更新。这是多种可能性之一。您可以使用
self.sample((num+rand()).floor)
,基本相同,无需提取
prob
@NeilSlater的值我喜欢这个想法,这基本上就是我所希望的。出色的逻辑,@NeilSlater+1