首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Ruby #用随机数检测行为

Ruby #用随机数检测行为
EN

Stack Overflow用户
提问于 2013-01-31 22:59:02
回答 1查看 164关注 0票数 5

在下面的Ruby代码中,我有两个方法d100_in_detectd100_out_detect,它们根据Array的结果返回ary中包含的唯一元素(简单起见是数字)的d100

代码语言:javascript
复制
def d100
  1 + ( rand 100 )
end

def d100_in_detect( ary )
  choice = [ ]
  100.times do
    choice.push ary.detect { |el| d100 <= el }
  end
  choice.uniq.sort
end

def d100_out_detect( ary )
  choice  = [ ]
  numbers = [ ]

  100.times do
    numbers.push d100
  end

  numbers.each do |i|
    choice.push ary.detect { |el| i <= el }
  end

  choice.uniq.sort
end

如你所见,这两种方法的不同之处在于,在第一种方法中,d100是在detect的块中调用的,而在第二种方法中,100个随机数被存储在numbers数组中,然后像在d100_in_detect中一样被使用。

假设我按如下方式调用这两个方法

代码语言:javascript
复制
ary = [ ]
50.times do |i|
  ary.push i * 5 
end

puts '# IN DETECT #'
print d100_in_detect ary
puts

puts '# OUT DETECT #'
puts d100_out_detect ary
puts

典型的输出如下。

代码语言:javascript
复制
# IN DETECT #
[ 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55 ]
# OUT DETECT #
[ 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100 ]

我不明白为什么这两个方法返回如此不同的结果。在detect的代码块中调用d100方法有什么含义吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-02-01 00:28:01

正确的。

我做的第一件事就是修改你的示例脚本:

代码语言:javascript
复制
def d100_in_detect( ary )
  choice = [ ]
  numbers = []
  100.times do
    var = d100
    numbers << var
    choice.push ary.detect { |el| var <= el }
  end
  puts numbers.inspect
  choice.uniq.sort
end

def d100_out_detect( ary )
  choice  = [ ]
  numbers = [ ]

  100.times do
    numbers.push d100
  end
  puts numbers.inspect

  numbers.each do |i|
    choice.push ary.detect { |el| i <= el }
  end

  choice.uniq.sort
end

正如你所看到的,我所做的就是将d100的结果赋给一个临时变量,看看happening....and到底是什么,“bug”消失了!我的返回值突然变得相同了。嗯。

然后,我突然想到了到底发生了什么。当你“缓存”变量时(就像你在第二个例子中所做的那样),你保证你有一个100个数字的分布。

在遍历该块时,对于该块中的每个数字,都会再次执行d100。因此,第一个one...but的调用次数比第二个多得多,您还需要在调用该数字时随机生成的数字大于该数字(然而,如果您用2随机生成100,则可以保证在某个时刻它将达到100 )。这种明显的偏向是你的脚本偏向于较低的数字!

例如,运行:

代码语言:javascript
复制
@called_count = 0
def d100
  @called_count += 1
  1 + ( rand 100 )
end

def d100_in_detect( ary )
  choice = [ ]
  numbers = []
  100.times do
    choice.push ary.detect { |el| d100 <= el }
  end
  puts @called_count.inspect
  @called_count = 0
  choice.uniq.sort
end

def d100_out_detect( ary )
  choice  = [ ]
  numbers = [ ]

  100.times do
    numbers.push d100
  end
        puts @called_count.inspect
  @called_count = 0

  numbers.each do |i|
    choice.push ary.detect { |el| i <= el }
  end

  choice.uniq.sort
end

我得到了

代码语言:javascript
复制
# IN DETECT #
691
# OUT DETECT #
100
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14628731

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档