I\'m either looking for an algorithm or a suggestion to improve my code to generate a list of random numbers that their sum equals some arbitrary number. With my code below
Here's how I would do it:
max
]max
and the first interval will start at 0 and end at the first number in the list.Now, the lengths of those intervals will always sum up to max
, since they simply represent segments inside [0,max
].
Code (in Python):
#! /usr/bin/env python
import random
def random_numbers(n,sum_to):
values=[0]+[random.randint(0,sum_to) for i in xrange(n-1)]+[sum_to]
values.sort()
intervals=[values[i+1]-values[i] for i in xrange(len(values)-1)]
return intervals
if __name__=='__main__':
print random_numbers(5,100)