Created
September 6, 2013 22:17
-
-
Save itolosa/6470717 to your computer and use it in GitHub Desktop.
PRNG - creates no repeated numbers
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
import random | |
import os | |
import time | |
import json | |
def calculateSeed(): | |
return reduce(lambda x,y: x+y, map(int, list(str(11*((int(time.time()) << os.getpid()) >> int(time.time()/400000))/7)))) | |
class CodeGen(object): | |
def __init__(self): | |
'''Hash Like Pseudo Random Number Generator''' | |
self.dbfilename = 'dbrandom.json' | |
fp = open(self.dbfilename) | |
seednum = calculateSeed() | |
random.seed(seednum) | |
print 'initialized with seed:', seednum | |
try: | |
self.usedkeys = json.load(fp) | |
except Exception: | |
self.usedkeys = list() | |
fp.close() | |
self.nbytes = 5 | |
self.maxnum = 4 | |
#cantidad de numeros a generar | |
self.nnum = 300 | |
def __hash(self, n, maxnum): | |
num = random.randint(0, maxnum) | |
s = list('qwertypsdfghjklzxcvbnm') | |
sn = list('1234567890') | |
random.shuffle(s) | |
random.shuffle(sn) | |
s = s[len(s)//2:] + s[:len(s)//2] | |
j = random.sample(s, n-num) + random.sample(sn, num) | |
for _ in range(3): | |
random.shuffle(j) | |
result = j[n//2:]+j[:n//2] | |
random.shuffle(result) | |
return ''.join(result)[::-1] | |
def flush(self): | |
fp = open(self.dbfilename, 'w') | |
json.dump(self.usedkeys, fp) | |
fp.close() | |
def gen(self): | |
try: | |
for _ in xrange(self.nnum): | |
code = self.hash(self.nbytes, self.maxnum) | |
while code in self.usedkeys: | |
code = self.__hash(self.nbytes, self.maxnum) | |
self.usedkeys.append(code) | |
except Exception: | |
self.flush() | |
def get_winner(self): | |
print random.choice(self.usedkeys) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment