Created
June 18, 2018 15:14
-
-
Save jaredlt/0ce23b338dd8fcc5962c2fb6451dd532 to your computer and use it in GitHub Desktop.
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
# https://www.quantamagazine.org/mathematicians-discover-prime-conspiracy-20160313/ | |
# | |
# If Alice tosses a coin until she sees a head followed by a tail, and Bob tosses a | |
# coin until he sees two heads in a row, then on average, Alice will require four tosses | |
# while Bob will require six tosses (try this at home!), even though head-tail and head-head | |
# have an equal chance of appearing after two coin tosses. | |
require 'pry' | |
def toss_coin | |
if rand.round == 0 | |
coin = "H" | |
else | |
coin = "T" | |
end | |
end | |
@HT_tosses = [] | |
@HH_tosses = [] | |
def check_coin_toss_result(coin_toss_history, person) | |
if person == :alice | |
if coin_toss_history.last(2).count == 2 | |
if coin_toss_history.last(2) == ["H", "T"] | |
@HT_tosses << coin_toss_history.count | |
return true | |
else | |
return false | |
end | |
else | |
return false | |
end | |
elsif person == :bob | |
if coin_toss_history.last(2).count == 2 | |
if coin_toss_history.last(2) == ["H", "H"] | |
@HH_tosses << coin_toss_history.count | |
return true | |
else | |
return false | |
end | |
else | |
return false | |
end | |
end | |
end | |
def coin_toss_round(person) | |
coin_toss_history = [] | |
check_result = false | |
while check_result == false | |
coin_toss_history << toss_coin | |
check_result = check_coin_toss_result(coin_toss_history, person) | |
end | |
end | |
# binding.pry | |
10000.times do |count| | |
coin_toss_round(:alice) | |
coin_toss_round(:bob) | |
printf "\rRound: #{count} Alice (HT average tosses): #{(@HT_tosses.inject{ |sum, el| sum + el }.to_f / @HT_tosses.size).round(2)} Bob (HH average tosses): #{(@HH_tosses.inject{ |sum, el| sum + el }.to_f / @HH_tosses.size).round(2)}" | |
end | |
puts "" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment