Skip to content

Instantly share code, notes, and snippets.

@klappy
Created December 3, 2012 22:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save klappy/4198565 to your computer and use it in GitHub Desktop.
Save klappy/4198565 to your computer and use it in GitHub Desktop.
Heads or Tails
samples = 100000.times.with_object([]){|i,a|a.push ["heads","tails"].sample}
#always choose heads
samples.map{|coin|coin=="heads"}.group_by{|o|o}.map.with_object({}){|h,o|o[h[0]]=h[1].count}[true].to_f/1000
#alternate every other call
samples.map.with_index{|coin,i|coin==(i.even? ? "heads" : "tails")}.group_by{|o|o}.map.with_object({}){|h,o|o[h[0]]=h[1].count}[true].to_f/1000
#randomly choose
samples.map{|coin|coin==["heads","tails"].sample}.group_by{|o|o}.map.with_object({}){|h,o|o[h[0]]=h[1].count}[true].to_f/1000
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment