Created
May 5, 2011 20:58
-
-
Save samwho/957915 to your computer and use it in GitHub Desktop.
A simulation of the ten letters, ten envelopes problem.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Original puzzle: A secretary receives 10 letters along with 10 addressed | |
# envelopes to be sent out. She accidentally drops the all the letters and | |
# envelopes and mixes them all up. So, she decides to put each of the 10 | |
# letters randomly into one of the 10 addressed envelopes and mail them out. | |
# What is the probability that at least one letter arrives at the correct | |
# destination? | |
# Gets a hash that represents the envelopes containing their randomly placed | |
# letter. Both envelope and letter are represented by a number. If the key and | |
# the value of each item in the hash are the same, that is a correct | |
# combination. | |
def get_envelopes | |
letters = [1,2,3,4,5,6,7,8,9,10] | |
envelopes = {1 => nil, 2 => nil, 3 => nil, 4 => nil, 5 => nil, 6=> nil, | |
7 => nil, 8 => nil, 9=> nil, 10 => nil} | |
10.times do |n| | |
index = rand(letters.count) | |
envelopes[n+1] = letters[index] | |
letters.delete_at(index) | |
end | |
return envelopes | |
end | |
# Takes a hash and compares the key and the value. If they match, it increments | |
# a count. When the hash has been looped over, the count is returned. | |
def count_correct_envelopes(envelopes) | |
count = 0 | |
envelopes.each do |key, value| | |
if key == value then | |
count += 1 | |
end | |
end | |
return count | |
end | |
# Number of simulations to run. | |
simulations = 50000 | |
# A hash that will eventually contain the count for how many envelopes | |
# contained the correct letter in them. | |
correct_envelopes = {0 => 0, 1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 => 0, 6=> 0, | |
7 => 0, 8 => 0, 9=> 0, 10 => 0} | |
# Run the simulation, count how many envelopes were correct each time | |
simulations.times do | |
correct_envelopes[count_correct_envelopes(get_envelopes)] +=1 | |
end | |
# Print the results. | |
at_least_one_correct = 0 | |
correct_envelopes.each do |key, value| | |
percent = ((value/simulations.to_f)*100) | |
puts key.to_s + " correct: " + percent.to_s + "%" | |
at_least_one_correct += percent if key > 0 | |
end | |
# Print the "At least 1" result. | |
puts "At least 1 correct: " + at_least_one_correct.to_s + "%" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment