Largest Remainder Allocation

Split a total across weighted shares with largest remainder allocation so the rounded parts always sum back to the total.

JavaData Integrity

Code

snippet
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));
    }
}

What the code does

Largest Remainder Allocation is built around the class RemainderAllocation and the functions allocate and main.

A single loop drives the file — for (double weight : weights).

Watch out for

  • Nothing needs adding to the project before it runs.

Using it

Signature: static int[] allocate(int total, double[] weights)

The demo output is labeled (shares:, sum matches total:), so the output doubles as a step-by-step trace of what the file did.

The sequence allocate lives in main; running the file triggers it.

Key statements

allocated += parts[i];
weightSum += weight;
parts[best] += 1;

Interactive Tools for This Topic

FAQ

What does Largest Remainder Allocation print when run?
No setup needed: run the file and look for labeled lines like `shares:`, `sum matches total:` in the output.