Skip to content

Instantly share code, notes, and snippets.

@jish
Last active December 31, 2015 05:09
Show Gist options
  • Select an option

  • Save jish/7939063 to your computer and use it in GitHub Desktop.

Select an option

Save jish/7939063 to your computer and use it in GitHub Desktop.
If I randomly guess a number between 1 & 1000, when will the numbers collide?
def detect_collision(number)
guessed_numbers = {}
count = 0
collision = false
while !collision
guess = rand(number)
count += 1
if guessed_numbers[guess]
collision = true
end
guessed_numbers[guess] = true
end
count
end
tries = 100
results = (1..tries).to_a.map do |i|
detect_collision(1_000)
end
puts results
sum = results.inject(0) { |memo, i| memo + i }
puts "Average: #{sum / tries}"
# ...
# 56
# 31
# 40
# 78
# 23
# 42
# 73
# 62
# 49
# 29
# Average: 39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment