Skip to content

Instantly share code, notes, and snippets.

@almost
Created December 1, 2012 15:27
Show Gist options
  • Save almost/4182887 to your computer and use it in GitHub Desktop.
Save almost/4182887 to your computer and use it in GitHub Desktop.
import random
# Generate n random numbers in the range start...end (inclusive) with no duplicates
# end-start must by a power of 2 minus 1 (so that we can keep on dividing into 2 without accounting for off by ones)
def rnd(start, end, n):
mid = (end-start)/2+start
assert end >= start
if n == 0:
return
# print "!", end-start
# print start, end, mid, n
if n > end-start:
for number in range(start,end+1):
yield number
return
# print (max(0, n-mid),min(n,mid))
in_first = random.randint(max(0, n-(mid+1)),min(n,mid+1))
# print in_first
for number in rnd(start, mid, in_first):
yield number
for number in rnd(mid+1, end, n-in_first):
yield number
def naive(start, end, n):
seen = set()
for i in range(n):
while True:
x = random.randint(start, end)
if x not in seen:
seen.add(x)
yield x
break
r = list(rnd(0, pow(2,64)-1, 10))
print len(r)
print r
# print list(sorted(naive(0, 128-1, 10)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment