它并不是特别有用,因为我过度使用了Numpy,但我会分享,因为它是相关的
import numpy import random # apple, bannana, grapes, guava, melon, pear fruits = numpy.array([100, 150, 175, 200, 230, 247]) # Bill, Bob, Dan, Fred, Joe ratios = numpy.array([21, 7, 32, 13, 27]) # Original fruit amount for each worker: 0 worker_fruits = numpy.zeros((5, 6), dtype=int) worker_lucky = numpy.zeros((5, 6), dtype=float) # For each worker with his ratio for worker, lucky, ratio in zip(worker_fruits, worker_lucky, ratios): # Give him fruits, storing partials as weighting to_give = (ratio * fruits) / 100 lucky += to_give % 1 worker += to_give # Calculate how much we have left over spares = fruits - worker_fruits.sum(axis=0) # Share it out in a weighted distribution for fruit, lucky, numspare in zip(worker_fruits.transpose(), worker_lucky.transpose(), spares): if numspare: indexes = numpy.arange(len(fruit)) add_to = numpy.random.choice(indexes, replace=False, size=numspare, p=lucky/numspare) fruit[add_to] += 1 # Our results! worker_fruits #>>> array([[21, 31, 36, 42, 49, 51], #>>> [ 7, 11, 12, 14, 16, 18], #>>> [32, 48, 56, 64, 74, 79], #>>> [13, 19, 23, 26, 29, 32], #>>> [27, 41, 48, 54, 62, 67]]) # Proof it's perfectly shared fruits - worker_fruits.sum(axis=0) #>>> array([0, 0, 0, 0, 0, 0])
使用双数学,向下舍入,然后根据比例随机分出剩余的水果。注意,你可以通过面向对象和循环使这不那么难看,但这是一个开始。
public void distribute(int apple, int pear, int grape) { double total = apple + pear + grape; double appleRatio = apple/total; double pearRatio = pear/total; double grapeRatio = grape/total; // apple worker int appleWorkerApple = (int) (appleRatio*apple); int appleWorkerPear = (int) (appleRatio*pear); int appleWorkerGrape = (int) (appleRatio*grape); // pear worker int pearWorkerApple = (int) (pearRatio*apple); int pearWorkerPear = (int) (pearRatio*pear); int pearWorkerGrape = (int) (pearRatio*grape); // grape worker int grapeWorkerApple = (int) (grapeRatio*apple); int grapeWorkerPear = (int) (grapeRatio*pear); int grapeWorkerGrape = (int) (grapeRatio*grape); int appleRemain = apple - appleWorkerApple - pearWorkerApple - grapeWorkerApple; int pearRemain = pear - appleWorkerApple - pearWorkerApple - grapeWorkerApple; int grapeRemain = grape - appleWorkerApple - pearWorkerApple - grapeWorkerApple; Random r = new Random(); while(appleRemain > 0 && pearRemain > 0 && grapeRemain > 0) { double target = r.nextDouble(); switch(r.nextInt(3)) { case 0: if(appleRemain > 0) { appleRemain-- if(target < appleRatio) appleWorkerApple++; else if (target < appleRatio + grapeRatio) pearWorkerApple++; else grapeWorkerApple++; } break; case 1: if(grapeRemain > 0) // etc. } } }