gpt4 book ai didi

Ruby #detect 使用随机数的行为

转载 作者:数据小太阳 更新时间:2023-10-29 07:18:35 25 4
gpt4 key购买 nike

在下面的 Ruby 代码中,我有两个方法 d100_in_detectd100_out_detect,它们返回包含在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 的 block 中调用的,而第二个是存储 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 的 block 中调用 d100 方法有什么含义吗?

最佳答案

没错。

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

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 的结果分配给一个临时变量以查看发生了什么……“错误”消失了!我的返回值突然变得相同。唔。

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

当您遍历该 block 时,对于 block 中的每个数字,您再次执行 d100。因此,第一个比第二个调用的次数大大...但是您还需要在调用该号码时随机生成的号码大于该号码(然而,如果您随机用 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 #
100

关于Ruby #detect 使用随机数的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14628731/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com