Sorted list with no sort, O(n)
If you want the integers sorted, I got to this answer in another question with a lot of help. You can do it using an exponential variate and thereby avoid any sort. As a result it is O(n):
From Alok's answer and Dan Dyer's comment it turns out that using an exponential distribution for a set of deltas gives a uniform distribution of integers in sequence.
So, you just start generating numbers and then scale them at the end. Adding 1 to the delta ensures you never repeat a value.
import random,sys,math
def genSortedInts(mini,maxi,vals):
running = 0
deltas = [random.expovariate(1.0) for i in range(0,vals+1)]
floats = []
for d in deltas:
running += d
floats.append(running)
upper = floats.pop()
valRange = maxi-mini-(vals-1)
ints = [mini+int(f/upper*valRange)+id for id,f in enumerate(floats)]
return ints
if __name__ == "__main__":
vals = 10
maxi = 80
mini = 0
print(genSortedInts(mini,maxi,vals))
Note the use of random.expovariate(1.0)
, a Python exponential distribution random number generator (very useful!). Here it's called with a mean of 1.0 (arg is 1/mean), but since the script normalises against the last number in the sequence, the mean itself doesn't matter.
Output (fair dice roll) for 10 values up to 80:
[3, 5, 10, 16, 25, 37, 41, 45, 57, 70]