Created
September 8, 2017 18:16
-
-
Save Akdeniz/91a16867ab6e4f58a09a8cb030e84c82 to your computer and use it in GitHub Desktop.
python script to generate random integer sequence
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
#!/usr/bin/python | |
""" | |
Generates unique random integers. | |
http://preshing.com/20121224/how-to-generate-a-sequence-of-unique-random-integers/ | |
""" | |
class RandomUniqueSequenceInt64: | |
_PRIME = 18446744073709551557 | |
def __init__(self, seed_base=0xDEADBEEFDEADBEEF, seed_offset=0xDEADBEEFDEADBEF0): | |
self.index = RandomUniqueSequenceInt64.permute_qpr( | |
RandomUniqueSequenceInt64.permute_qpr(seed_base) + 0x682f0161) | |
self.intermediate_offset = RandomUniqueSequenceInt64.permute_qpr( | |
RandomUniqueSequenceInt64.permute_qpr(seed_offset) + 0x4679090546790905) | |
def next(self): | |
result = RandomUniqueSequenceInt64.permute_qpr( | |
(RandomUniqueSequenceInt64.permute_qpr(self.index) + self.intermediate_offset) ^ 0x5bf036355bf03635) | |
self.index += 1 | |
return result | |
@staticmethod | |
def permute_qpr(x): | |
if x > RandomUniqueSequenceInt64._PRIME: | |
return x | |
residue = (x * x) % RandomUniqueSequenceInt64._PRIME | |
return residue if (x <= RandomUniqueSequenceInt64._PRIME / 2) else RandomUniqueSequenceInt64._PRIME - residue | |
class RandomUniqueSequenceInt32: | |
_PRIME = 4294967291 | |
def __init__(self, seed_base=0xDEADBEEF, seed_offset=0xDEADBEF0): | |
self.index = RandomUniqueSequenceInt32.permute_qpr( | |
RandomUniqueSequenceInt32.permute_qpr(seed_base) + 0x682f0161) | |
self.intermediate_offset = RandomUniqueSequenceInt32.permute_qpr( | |
RandomUniqueSequenceInt32.permute_qpr(seed_offset) + 0x46790905) | |
def next(self): | |
result = RandomUniqueSequenceInt32.permute_qpr( | |
(RandomUniqueSequenceInt32.permute_qpr(self.index) + self.intermediate_offset) ^ 0x5bf03635) | |
self.index += 1 | |
return result | |
@staticmethod | |
def permute_qpr(x): | |
if x > RandomUniqueSequenceInt32._PRIME: | |
return x | |
residue = (x * x) % RandomUniqueSequenceInt32._PRIME | |
return residue if (x <= RandomUniqueSequenceInt32._PRIME / 2) else RandomUniqueSequenceInt32._PRIME - residue | |
if __name__ == '__main__': | |
rus = RandomUniqueSequenceInt32() | |
N = 100 * 1000 * 1000 * 2 | |
for i in xrange(N): | |
print rus.next() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment