Skip to content

Instantly share code, notes, and snippets.

@mvw
Last active November 5, 2016 18:55
Show Gist options
  • Save mvw/ce8a991760d460ea7f81b743feb862e1 to your computer and use it in GitHub Desktop.
Save mvw/ce8a991760d460ea7f81b743feb862e1 to your computer and use it in GitHub Desktop.
# http://math.stackexchange.com/q/2000829/86776
require 'set'
class Jar
@cookies
def initialize
@cookies = Set.new
(1..10).each do |k|
@cookies.add(k)
end
end
def to_s
a = @cookies.to_a
s = '{ ' + a.join(', ') + ' }'
end
def eat
@cookies.each do |cookie|
r = rand(2)
if r == 1
@cookies.delete(cookie)
end
end
end
def empty?
@cookies.empty?
end
end
def run
jar = Jar.new
d = 0
begin
jar.eat
d += 1
#puts "d: #{d} jar: #{jar}"
end while not jar.empty?
d
end
def sim
n = 1_000_000
s = 0
n.times do |k|
d = run
s += d
end
avg = s * 1.0 / n
puts "n = #{n}, avg = #{avg}"
end
sim
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment