Last active
December 31, 2015 05:09
-
-
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?
This file contains hidden or 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
| 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