problem with a little ruby script
i just began learning ruby. now im trying to code a little script which plays the montyhall problem i got a problem with the last line of the code
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 ? door开发者_运维知识库s[0] : guess end
puts "You decided #{switch ? "" : "not "}to switch, and your win % is #{wins.times ()/numgames}"
In the last line replace
wins.times ()
with
wins
times
returns Enumerator
, which doesn't play well with division.
Two problems:
First, wins
and numgames
are integers, and integer division returns an integer:
irb(main):001:0> 6632 / 10000
=> 0
So, change wins = 0
to wins = 0.0
. This will force a floating point division, which will return a floating point answer.
Second, wins
is a number, not an array. So get rid of wins.times()
and wins.size()
. Both are wrong.
With these two changes in place, I consistently get around 66% wins, which just goes to show that Marilyn vos Savant is way smarter than I am.
Your wins
is an integer so you don't need .times
or .size
, you do, however, want .to_f
to force things into floating point mode:
wins.to_f / numgames
And if you want a percentage, then you'll have to multiply by 100:
wins.to_f / numgames * 100
You should also properly indent your code for readability and break things up with line breaks to make it easier to read and easier for the parser to figure out:
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}"
精彩评论