在下面的Ruby代码中,我有两个方法d100_in_detect和d100_out_detect,它们根据Array的结果返回ary中包含的唯一元素(简单起见是数字)的d100。
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中一样被使用。
假设我按如下方式调用这两个方法
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典型的输出如下。
# 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方法有什么含义吗?
发布于 2013-02-01 00:28:01
正确的。
我做的第一件事就是修改你的示例脚本:
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 )。这种明显的偏向是你的脚本偏向于较低的数字!
例如,运行:
@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我得到了
# IN DETECT #
691
# OUT DETECT #
100https://stackoverflow.com/questions/14628731
复制相似问题