实现说明
除了类 RemainderAllocation和函数 allocate、main,文件里再无其他定义。
文件的主干是一个循环——for (double weight : weights)。
使用要点
- 每一步打印都带着自己的标签:
shares:、sum matches total:。 main按顺序串起allocate;运行文件就会把这个流程跑一遍。
常见问题
运行「最大余数法分摊」会打印什么?
运行文件本身,shares:、sum matches total: 这些前缀各对应一段演示逻辑。
入口签名:static int[] allocate(int total, double[] weights)
核心语句
allocated += parts[i];
weightSum += weight;
parts[best] += 1;
代码示例
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Arrays;
public class RemainderAllocation {
// largest remainder allocation: floor each share proportionally, then hand the remainder out one seat at a time by largest fractional part
static int[] allocate(int total, double[] weights) {
double weightSum = 0;
for (double weight : weights) {
weightSum += weight;
}
int[] parts = new int[weights.length];
BigDecimal[] fractional = new BigDecimal[weights.length];
int allocated = 0;
for (int i = 0; i < weights.length; i++) {
BigDecimal exact = BigDecimal.valueOf(total)
.multiply(BigDecimal.valueOf(weights[i]))
.divide(BigDecimal.valueOf(weightSum), 6, RoundingMode.HALF_UP);
parts[i] = exact.intValue();
fractional[i] = exact.subtract(BigDecimal.valueOf(parts[i]));
allocated += parts[i];
}
int leftover = total - allocated;
while (leftover-- > 0) {
int best = 0;
for (int i = 1; i < fractional.length; i++) {
if (fractional[i].compareTo(fractional[best]) > 0) {
best = i;
}
}
parts[best] += 1;
fractional[best] = BigDecimal.ZERO;
}
return parts;
}
public static void main(String[] args) {
int[] shares = allocate(10, new double[] {1, 1, 1});
System.out.println("shares: " + Arrays.toString(shares));
System.out.println("sum matches total: "
+ (shares[0] + shares[1] + shares[2] == 10));
}
}