Skip to content

Instantly share code, notes, and snippets.

@typeswitch-dev
Last active March 1, 2020 11:30
Show Gist options
  • Save typeswitch-dev/6616031843abb8823cd597522dc5b809 to your computer and use it in GitHub Desktop.
Save typeswitch-dev/6616031843abb8823cd597522dc5b809 to your computer and use it in GitHub Desktop.
Approximates e using bogosort.
# Calculates e using randomized bogosort. The average number
# of comparisons per round should be close to e-1 due to
# shortcircuiting, so we run bogosort and keep track of
# the number of rounds and number of comparisons, and use
# that to calculate e.
import random
n = 10
xs = list(range(n)) # start with a sorted list to rub it in.
num_rounds = 0
num_comparisons = 0
done = False
while not done:
num_rounds += 1
random.shuffle(xs)
done = True
for i in range(n-1):
num_comparisons += 1
if xs[i] > xs[i+1]:
done = False
break
print('n:', n)
print('num_rounds:', num_rounds)
print('num_comparisons:', num_comparisons)
print('e:', 1 + num_comparisons/num_rounds)
@typeswitch-dev
Copy link
Author

typeswitch-dev commented Mar 1, 2020

Sample output:

$ python3 bogosort_approximator.py 
n: 10
num_rounds: 5583731
num_comparisons: 9595517
e: 2.7184776630536103

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment