Created
October 21, 2014 17:09
-
-
Save raidzero/1514c9a4f9ff9e1d440b to your computer and use it in GitHub Desktop.
Split N into X uniformly-distributed pieces
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/python2.7 | |
import sys | |
from random import randrange | |
def split(n, numPieces): | |
rtn = [] | |
for i in range(numPieces): | |
# get a good starting position to deviate from | |
mid = n // numPieces | |
if i % 2 == 0: | |
# only get a new random delta every other iteration | |
delta = randrange(0, mid) | |
else: | |
delta = -delta | |
# if odd, dont change the last number in the set | |
if numPieces % 2 != 0 and i == numPieces - 1: | |
delta = 0 | |
rtn.append(mid + delta) | |
numSum = sum(rtn) | |
# remainders? | |
if (numSum > n): | |
diff = n - numSum | |
else: | |
diff = numSum - n | |
# now distribute the remainder back into the set, if necessary | |
if diff != 0: | |
for i in range(0, abs(diff)): | |
# get a random index | |
index = randrange(0, numPieces) | |
if diff > 0: # negative | |
rtn[index] = rtn[index] - 1 | |
else: # positive | |
rtn[index] = rtn[index] + 1 | |
print "sum: %d" % sum(rtn) | |
return rtn | |
print split(int(sys.argv[1]), int(sys.argv[2])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment