一个小红宝石脚本的问题

时间:2011-03-12 05:12:34

标签: ruby

我刚开始学习红宝石。 现在我试图编写一个播放montyhall问题的小脚本 我的代码的最后一行有问题

numgames = 10000 # Number of games to play 
switch = true # Switch your guess?
wins = 0
numgames.times do doors = [0, 0, 0] # Three doors! 
doors[rand(3)] = 1 # One of them has a car! 
guess = doors.delete_at(rand(3)) # We pick one of them!
doors.delete_at(doors[0] == 0 ? 0 : 1) # Take out one of the remaining doors that is not a car! 
wins += switch ? doors[0] : guess end
puts "You decided #{switch ? "" : "not "}to switch, and your win % is #{wins.times ()/numgames}"

3 个答案:

答案 0 :(得分:2)

在最后一行替换

wins.times ()

wins

times会返回Enumerator,这与分割效果不佳。

答案 1 :(得分:1)

两个问题:

首先,winsnumgames是整数,整数除法返回一个整数:

irb(main):001:0> 6632 / 10000
=> 0

所以,将wins = 0更改为wins = 0.0。这将强制浮点除法,它将返回浮点答案。

其次,wins是一个数字,而不是一个数组。所以摆脱wins.times() wins.size()。两者都错了。

有了这两个变化,我一直获得66%的胜利,这只是表明Marilyn vos Savant 方式比我聪明。

答案 2 :(得分:0)

您的wins是一个整数,因此您不需要.times.size,但是,您希望.to_f强制进入浮点模式:< / p>

wins.to_f / numgames

如果你想要一个百分比,那么你将不得不乘以100:

wins.to_f / numgames * 100

您还应该正确地缩进代码以提高可读性,并使用换行符来解决问题,以便更容易阅读并使解析器更容易理解:

numgames = 10000 # Number of games to play
switch = true # Switch your guess?
wins = 0
numgames.times do
    doors = [0, 0, 0] # Three doors!
    doors[rand(3)] = 1 # One of them has a car!
    guess = doors.delete_at(rand(3)) # We pick one of them!
    doors.delete_at(doors[0] == 0 ? 0 : 1) # Take out one of the remaining doors that is not a car!
    wins += switch ? doors[0] : guess
end
puts "You decided #{switch ? "" : "not "}to switch, and your win % is #{100 * wins.to_f / numgames}"