使用双倍数学,四舍五入,然后根据比率随机分发剩余的水果。请注意,使用对象方向和循环可以使其不那么难看,但这只是一个开始。在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.
}
}
}