Skip to content

Instantly share code, notes, and snippets.

@finiteautomata
Last active May 15, 2017 18:17
Show Gist options
  • Save finiteautomata/bef2b2829b631e59ff5f7a3fa9736977 to your computer and use it in GitHub Desktop.
Save finiteautomata/bef2b2829b631e59ff5f7a3fa9736977 to your computer and use it in GitHub Desktop.
Function that returns a list of m integers that sums n
import random
def random_balls_in_bins(balls, bins):
"""
Returns a list of <bins> integers that sum <balls>
We can think this as a problem of bosons:
We have to distribute balls in bins. To model this, we use a shuffle of
'o' * balls + '|' * (bins-1)
This results in a string of the form oo|ooo|oo where we leave the last '|' fixed
Parameters:
----------
balls: int > 0
number of balls to distribute
bins: int > 0
number of bins
Returns
-------
A list of <bins> integers that sum <balls>
"""
balls_and_bins = list('o' * balls + '|' * (bins-1))
random.shuffle(balls_and_bins)
bins = []
current = 0
for e in balls_and_bins:
if e == 'o':
current +=1
elif e == '|':
bins.append(current)
current = 0
bins.append(current)
return bins
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment