Created
June 29, 2018 21:20
-
-
Save itdaniher/4dc5088d0c904b38b42029ef50a1555a to your computer and use it in GitHub Desktop.
true random number generator based (d20) dice roller, verified fair
This file contains 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
f = open('/dev/urandom', 'rb') | |
default_n = 1000000 | |
max_r = 256 | |
def r1dx(x=20): | |
while True: | |
# get one byte, take as int on [1,256] | |
r = int.from_bytes(f.read(1), 'little')+1 | |
# if byte is less than the max factor of 'x' on the interval max_r, return r%x+1 | |
if r < (max_r-(max_r%x)+1): return (r%x)+1 | |
if __name__ == "__main__": | |
import itertools | |
# get N sorted values taken from r1dx() | |
def sample(n=default_n): return sorted([r1dx() for _ in range(n)]) | |
# run-length encoding | |
def rle(xs): return [(len(list(gp)), x) for x, gp in itertools.groupby(xs)] | |
# print a table of the decimal rate of occurrence for each value | |
print('\n'.join(["%.4f %d" % (x[0]/default_n, x[1]) for x in rle(sample())])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment