Skip to content

Instantly share code, notes, and snippets.

@nwwells
Created October 13, 2015 17:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nwwells/89a648987e800dc2e079 to your computer and use it in GitHub Desktop.
Save nwwells/89a648987e800dc2e079 to your computer and use it in GitHub Desktop.
Coding challenge for Symbiont
#!/usr/bin/env python
import io
import os
import sys
import random
import atexit
fifo_path = "/tmp/rander.{0}".format(os.getpid())
def init(fifo_path):
os.mkfifo(fifo_path)
print "writing random bits to {0}".format(fifo_path)
def end(fifo_path):
print "ending randomness"
os.remove(fifo_path)
atexit.register(end, fifo_path)
def main(fifo_path):
init(fifo_path)
#write random bits endlessly to fifo
while True:
try:
fifo = io.open(fifo_path, "wb")
while fifo.writable():
fifo.write(chr(random.randrange(255)))
except KeyboardInterrupt:
break;
except IOError:
print "pipe broke, reopening..."
except:
print "Unexpected error:", sys.exc_info()[0]
break;
#atexit will clean up the fifo
main(fifo_path)
#!/usr/bin/env python
import io
print "Loading randomness..."
path = "/tmp/rander.66733" # insert pipe here...
num_bytes = 100000000
bits_to_shift = 4
number_of_groups = 2 ** bits_to_shift
rand = io.open(path, "rb")
samples = [0] * number_of_groups
byte_values = rand.read(num_bytes)
ordinal_samples = [ord(c) >> bits_to_shift for c in byte_values]
for occurence in ordinal_samples:
samples[occurence] += 1
print samples
maximum = max(samples)
minimum = min(samples)
mean = float(sum(samples)) / len(samples)
expected_mean = num_bytes / number_of_groups
print "Maximum: {0} [{1}]".format(maximum, samples.index(maximum))
print "Minimum: {0} [{1}]".format(minimum, samples.index(minimum))
print "Range: {0}".format(maximum - minimum)
print "Expected: {0}".format(expected_mean)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment