Case study: expense sharing
What you will learn on this page
Section titled “What you will learn on this page”- Why money is a whole number of cents, and what goes wrong with a
double, even for a bill of 10.00 split three ways. - How to model three ways of splitting a bill (equally, by exact
amounts, by percent) as one
std::variant, and why that beats a Strategy class hierarchy here, and when it would not. - How one rounding rule, used for every split, makes the shares add up to the bill exactly, gives each person their fair share to within a cent, and splits the same bill the same way every time.
- How a group keeps an invariant, that the balances add up to zero, and how a test with thousands of random expenses checks it.
- How to suggest who pays whom to settle up, and why the simple answer is not always the shortest one.
- How a change (expenses in other currencies, at fixed rates) lands: one conversion, in one place, and the invariant still holds to the cent.
This page follows the order in How to approach a case study. It assumes Strong types and API contracts and Property-based and table-driven tests. The second of those uses a bill split as its running example and builds the rounding rule from its properties; this page puts that rule inside a whole program and shows what else has to be true around it.
The request
Section titled “The request”“Our friends go away together a few times a year, and the spreadsheet we use is a mess. Someone pays for dinner, someone else for the taxi, the hotel is split by room. At the end nobody agrees who owes what, and last time the totals were off by a few cents and we argued about that too. Can you design the part that splits expenses and tells us how to settle up?”
Two complaints hide in here. “Nobody agrees who owes what” is about a single, trusted record of balances. “Off by a few cents” is about rounding: a bill that does not divide evenly must still be shared out exactly, by a rule that everyone can check.
Clarifying questions
Section titled “Clarifying questions”Each question is here because its answer changes the design.
| Question | Answer (from the group) | What it changes |
|---|---|---|
| How can a bill be split? | Equally among some of us, by exact amounts (the hotel by room), or by percent. | Three kinds of split, and no others for now: a closed set. |
| Does the person who paid always share the bill? | No. Sometimes one person buys a gift for the others. | The payer and the people sharing are separate lists. |
| Percents with decimals, such as 33.3%? | No, whole percents are enough. | A percent is an int, 0 to 100, and they must add up to exactly 100. |
| When 10.00 is split three ways, who pays the extra cent? | We don’t mind, as long as it is always the same rule and nobody pays more than a cent extra. | One rounding rule, used for every split, with a tie rule that does not depend on chance. |
| What if someone types a split that does not add up? | Tell them what is wrong, and do not save it. | Validation with a reason for each refusal, and a refused expense changes nothing. |
| What do we want to see at the end? | How much each person is up or down, and who should pay whom. | A balance per member, and a settle-up plan of transfers. |
| Must the plan have the fewest payments possible? | Few is good. It must be the same plan if we ask twice. | A simple greedy rule, honest about not being minimal, and repeatable. |
| Do you need the list of past expenses, edits, or undo? | Not yet. | The group keeps balances, not history. Edits and deletion are out of scope. |
| How big can an expense be? | Nothing near ten million. | A cap of 10,000,000.00 per expense, which also keeps the arithmetic inside std::int64_t. |
| One currency? | For now. Some of our trips are abroad, though. | One currency in step 1. Several currencies arrive later as a change. |
| Several people adding expenses at the same time? | One phone, one person typing, for now. | Single-threaded and in memory, and the page says so. |
Three answers decide the shape. “Always the same rule, and nobody pays more than a cent extra” pins the rounding down to one function with a testable promise. “Tell them what is wrong, and do not save it” makes a refusal an ordinary value with a reason, and makes every change all or nothing. “The same plan if we ask twice” rules out anything that depends on hash order, memory addresses, or chance.
Confirmed:
- A group of named members, set up once.
- Expenses with a payer, an amount, and a split: equal among some members, exact amounts, or whole percents.
- Shares in whole cents that add up to the amount exactly, by one rule.
- Refusals with a reason, which leave the group unchanged.
- A balance per member, and a suggested list of transfers to settle up.
- Recording a transfer when someone pays someone back.
Assumed (to confirm with the group; see Assumptions):
- A member’s name is unique in the group and does not change. It is the member’s id.
- The order in which members are listed in a split is meaningful: it breaks ties when a cent is left over. The person typing chooses it.
- An amount has two decimal places (cents). Step 2 keeps that assumption for every currency, and says where it breaks.
Out of scope: accounts and sign-in, a history of expenses, editing or deleting an expense, receipts, real payments, storage, and sync between devices. Several currencies arrive as a change, below.
Requirements
Section titled “Requirements”Functional requirements.
- FR-1 Group. A group has at least one member, each with a non-empty name that appears once. A group set up wrong is refused when it is created.
- FR-2 Expense. An expense has a description, a payer who is a member, a positive amount up to the cap, and a split. The payer need not be among the people who share it.
- FR-3 Splits. A split is one of: equal among a list of members; exact amounts per member, which add up to the amount; percent per member, whole percents that add up to 100. Nobody appears twice in one split, and everyone named is a member.
- FR-4 Rounding. Every share is a whole number of cents. The shares add up to the amount exactly. Each share is the exact fair share rounded down or up, never further off than one cent. The same expense always splits the same way.
- FR-5 Refusals. An expense or transfer that breaks a rule is refused with a reason and a sentence for the person, and the group is unchanged.
- FR-6 Balances. Each member has a balance: what they paid, less what they owe, plus what they paid back, less what they were paid back.
- FR-7 Settle up. The group can suggest transfers that bring every balance to zero, at most one fewer than the number of members, the same every time for the same balances. A transfer between two members can be recorded.
Non-functional requirements.
- NFR-1 Exact money. Amounts are integer cents, never floating point.
- NFR-2 Repeatable. Results depend only on the input and its order: no hash order, no addresses, no randomness.
- NFR-3 No overflow. Every product and sum the code forms fits in
std::int64_t, for every amount it accepts. - NFR-4 Testable without set-up. Splitting is a pure function of the expense and the member list.
- NFR-5 Single-threaded, in memory. One caller at a time, and nothing is saved. The documentation says so.
FR-4 is the “off by a few cents” complaint, written as something a test can check. Most of the design below exists to keep it, and to keep the invariant that follows from it.
Use cases and acceptance criteria
Section titled “Use cases and acceptance criteria”The tests are named after these criteria. See Use cases, user stories, and acceptance criteria.
UC-1 Set up a group.
- AC-1.1 A new group has every member at a balance of zero.
- AC-1.2 An empty list, an empty name, or a name listed twice is refused.
UC-2 Split equally.
- AC-2.1 An amount that divides evenly gives everyone the same.
- AC-2.2 The cents left over go one each to the first members listed.
- AC-2.3 The same expense always splits the same way.
- AC-2.4 One cent among four goes to the first listed.
UC-3 Split by exact amounts.
- AC-3.1 Exact parts are owed as typed, including a part of zero.
- AC-3.2 Parts that do not add up to the amount, too little or too much, are refused, even a part so large that adding it would overflow.
- AC-3.3 A negative part is refused.
UC-4 Split by percent.
- AC-4.1 Percents that divide evenly give the exact amounts.
- AC-4.2 Percents that do not add up to 100 are refused; a negative percent is refused as negative.
- AC-4.3 A spare cent goes to whoever rounding down cost the most, not simply to the first listed.
- AC-4.4 When two lost the same, the one listed first gets the cent.
- AC-4.5 A member at 0% never gets a cent.
UC-5 Validate.
- AC-5.1 The amount must be more than zero and at most the cap; the cap itself is accepted.
- AC-5.2 The payer and everyone named in the split must be members.
- AC-5.3 A split must name someone, and nobody twice.
- AC-5.4 The payer need not share the expense.
UC-6 Keep the books balanced.
- AC-6.1 After every expense and transfer, accepted or refused, the balances add up to exactly zero.
- AC-6.2
allocategives out exactly the total, and every part is its exact share rounded down, or one cent more.
UC-7 Settle up.
- AC-7.1 Recording the suggested transfers brings everyone to zero, in at most one fewer transfers than members.
- AC-7.2 The biggest debtor pays the biggest creditor first; a tie goes to the name that sorts first.
- AC-7.3 Greedy is not always the fewest transfers: a case where it needs four and three are enough.
- AC-7.4 Nothing to settle gives an empty plan; balances that do not add up to zero are refused.
- AC-7.5 A transfer from or to a stranger, to oneself, or of an amount that is not positive or over the cap is refused and changes nothing.
Invariants
Section titled “Invariants”Each invariant names the code that keeps it. See Invariants.
- INV-1 Shares add up. The shares of an accepted expense add up to
its amount exactly. Kept by
allocate, which hands out the cents that rounding down left over, and by the exact-parts check insplit_expense. - INV-2 Fair to the cent. Every share made by
allocateis the exact share rounded down, or one cent more. Kept byallocate, which gives each part at most one extra cent. - INV-3 The balances add up to zero. Kept by
Group: an expense credits the payer exactly what it debits the members (INV-1), and a transfer adds to one member exactly what it takes from another. - INV-4 A refusal changes nothing. Kept by the order of the code:
split_expensechecks everything and changes nothing, andadd_expenseandrecord_transfertouch the balances only after every check has passed. - INV-5 Repeatable. The same input in the same order gives the same
shares and the same plan. Kept by integer arithmetic,
stable_sortwith the list order as the tie rule, and astd::mapthat walks names in sorted order.
The random test adds 3,000 random expenses, some of them invalid, and some transfers, and checks INV-1 for every accepted expense and INV-3 after every single step.
Entities and relationships
Section titled “Entities and relationships”The nouns from the answers: friend, group, bill, payer, amount, split, equal, exact, percent, cent, share, balance, payment back, plan. Filtered:
- Friend becomes a member, known by a
MemberId, a name. There is noMemberclass, because a member has no data or behaviour of their own yet beyond the name and the balance. - Group is a
Group: the member list and the balances. - Bill is an
Expense: a description, a payer, an amount, and a split. - Amount, cent, and balance are
Money, a count of cents. - Split is a
Split, one ofEqual,Exact, orPercent. - Share is a
Share: a member and the amount they owe. - Payment back is a
Transfer: from, to, and an amount. - Plan is the list of
Transfers thatsettle_upreturns. - A refusal becomes a
Rejection: aReasonand a sentence.
Text description of the diagram
Group owns a vector of member names and Balances, a map from each name to Money. It offers members, balances, add_expense, which takes an Expense and returns a SplitResult, and record_transfer, which takes a Transfer and returns an optional Rejection. An Expense holds a description, the payer’s name, an amount in Money, and a Split. A Split is a std::variant holding exactly one of Equal (a list of names), Exact (a list of name and Money pairs), or Percent (a list of name and whole percent pairs). Share is a name and an amount. Rejection is a Reason and a sentence. Transfer is from, to, and an amount. Money holds a count of cents in a 64-bit integer. Three free functions do the work: split_expense checks an expense and returns its shares or a rejection, allocate divides a total in proportion to weights, and settle_up turns balances into a list of transfers. Group’s add_expense calls split_expense.
Diagram source (Mermaid)
classDiagram
class Group {
-vector~MemberId~ members_
-Balances balances_
+members() const vector~MemberId~&
+balances() const Balances&
+add_expense(const Expense&) SplitResult
+record_transfer(const Transfer&) optional~Rejection~
}
class Expense {
+string description
+MemberId paid_by
+Money amount
+Split split
}
class Split {
<<variant>>
Equal
Exact
Percent
}
class Equal {
+vector~MemberId~ among
}
class Exact {
+vector~pair~MemberId, Money~~ parts
}
class Percent {
+vector~pair~MemberId, int~~ parts
}
class Share {
+MemberId member
+Money amount
}
class Rejection {
+Reason reason
+string detail
}
class Transfer {
+MemberId from
+MemberId to
+Money amount
}
class Money {
+int64_t cents
}
class SplitFunctions {
<<free functions>>
+split_expense(const Expense&, members) SplitResult
+allocate(Money, weights) vector~Money~
+settle_up(const Balances&) vector~Transfer~
}
Expense *-- Split : split
Split *-- Equal
Split *-- Exact
Split *-- Percent
Group ..> SplitFunctions : add_expense calls split_expense
SplitFunctions ..> Share : returns
SplitFunctions ..> Rejection : or returns
Group ..> Transfer : records
Group ..> Money : balances inOwnership is simple and worth saying out loud. Everything here is a
value: a Group owns its
member list and its balances as plain members, an Expense owns its
split, and a Split owns its list. Nothing is shared, nothing is held
by pointer, and copying a Group copies the whole group. That is the
right shape for a small, single-threaded model: there is no lifetime to
get wrong.
The work is done by free functions, not by methods on Group.
split_expense and allocate need nothing from a group but its list
of members, so they take only that, and a test can call them with no
group at all (NFR-4). settle_up takes balances and returns a plan; it
does not change the group, because a plan is a suggestion until someone
pays.
Class design
Section titled “Class design”The design below is step 1 of the example, the complete answer to FR-1 … FR-7. Several currencies are added in When the requirements change.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// An amount in cents. Never a double: 0.1 + 0.2 is not 0.3 in binary// floating point, and a group's balances must add up to exactly zero.// Negative amounts are allowed, because a balance can be negative.struct Money { std::int64_t cents = 0;
friend constexpr auto operator<=>(const Money&, const Money&) = default; friend constexpr Money operator+(Money a, Money b) { return {a.cents + b.cents}; } friend constexpr Money operator-(Money a, Money b) { return {a.cents - b.cents}; } friend constexpr Money operator-(Money a) { return {-a.cents}; } constexpr Money& operator+=(Money other) { cents += other.cents; return *this; } constexpr Money& operator-=(Money other) { cents -= other.cents; return *this; }};
[[nodiscard]] constexpr Money cents(std::int64_t count) { return {count}; }[[nodiscard]] constexpr Money units(std::int64_t whole) { return {whole * 100}; }
// The largest amount one expense or transfer may have: 10,000,000.00.// allocate multiplies an amount by a weight. In this step the largest// weight is a percent, 100, so the product is at most 10^11. Step 2 uses// exact parts, which can be as big as the amount, as weights, and the cap// keeps that product (at most 10^18) inside std::int64_t too.inline constexpr Money max_amount = cents(1'000'000'000);
// "120.00", or "-5.50".[[nodiscard]] inline std::string to_string(Money money) { const std::int64_t magnitude = money.cents < 0 ? -money.cents : money.cents; std::string fraction = std::to_string(magnitude % 100); if (fraction.size() < 2) fraction.insert(0, "0"); // 5 cents is ".05", not ".5" return (money.cents < 0 ? "-" : "") + std::to_string(magnitude / 100) + "." + fraction;}Money is a count of cents in a std::int64_t, with only the
operations a balance needs: add, subtract, negate, compare. It is a
small instance of Strong types: a function
that takes Money cannot be handed a percent or a count of people by
mistake. A negative amount is allowed, because a balance can be
negative; whether an expense may be negative is a rule of
split_expense, not of the type.
max_amount is there for arithmetic, not for business. allocate
multiplies an amount by a weight. In step 1 the largest weight is a
percent, 100, so the largest product is 1011. Step 2 uses
exact parts as weights, and a part can be as big as the amount, so
there the largest product is the cap times itself: 109
cents times 109 is 1018, which still fits in an
int64_t (whose largest value is about 9.2 × 1018). Without
the cap, a large enough expense would overflow, which for a signed integer is
undefined behaviour,
not just a wrong answer (NFR-3).
Splits and expenses
Section titled “Splits and expenses”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The three ways to split an expense. Each holds only the data its rule// needs, and the members are listed in the order the user gave them,// because that order breaks ties when cents are left over.struct Equal { std::vector<MemberId> among;};struct Exact { std::vector<std::pair<MemberId, Money>> parts; // each part in cents};struct Percent { std::vector<std::pair<MemberId, int>> parts; // whole percents, 0 to 100};
// A Split is exactly one of the three. A std::variant, not a Strategy// class hierarchy: the set of rules is closed and small, the validation// has to know which rule it is checking, and a variant is a plain value// that copies like any other, with no owning pointer and no virtual calls.// A hierarchy would earn its place only if new rules were added by code// that cannot edit this file.using Split = std::variant<Equal, Exact, Percent>;Each kind of split holds only what its rule needs. Equal has a list
of names. Exact and Percent pair each name with its number, so a
name can never drift out of line with its value, as it could in two
parallel lists. And Split is exactly one of the three, as
std::variant guarantees: there is no split that is “equal and also
has some percents”.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// One expense: who paid, how much, and how it is shared. The payer does// not have to be one of the people it is shared among.struct Expense { std::string description; MemberId paid_by; Money amount; Split split;};
// One member's part of an expense.struct Share { MemberId member; Money amount; friend bool operator==(const Share&, const Share&) = default;};using Shares = std::vector<Share>;VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Why an expense or a transfer was refused. The caller gets the reason as// a value, to show the user or to test, and the group is left unchanged.enum class Reason { amount_not_positive, amount_too_large, unknown_member, empty_split, duplicate_member, negative_part, exact_sum_mismatch, percent_sum_mismatch, same_member,};
struct Rejection { Reason reason; std::string detail; // a sentence for a person, naming what was wrong};
[[nodiscard]] std::string to_string(Reason reason);
// Either the shares of an accepted expense, or why it was refused.using SplitResult = std::variant<Shares, Rejection>;A refusal is a value, not an exception. A user who types parts
that do not add up has not found a bug in the program; it is an
ordinary outcome that every caller must handle, and SplitResult, a
variant of Shares or Rejection, makes the caller look at both. The
Reason is for code and tests; the detail is for a person. The
exceptions in this example are kept for a group set up wrong, a
programming error in the caller.
The rounding rule
Section titled “The rounding rule”Every split that can leave cents over (equal and percent) goes through
one function, allocate. It takes a total and a list of weights and
divides the total in proportion to them: an equal split is weights of
1, 1, 1; a split of 50%, 25%, 25% is weights of 50, 25, 25.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Divides total into parts in proportion to weights, in whole cents, so// that the parts always add up to exactly total.//// Each part first gets the rounded-down share total * weight / sum. The// cents left over (fewer than the number of parts) go one each to the// parts that lost the largest fraction of a cent; when two lost the same// fraction, the one earlier in the list gets the cent. The result depends// only on the arguments and their order, never on memory addresses, hash// order, or chance, so the same expense always splits the same way.//// Expects total >= 0, every weight >= 0, and a positive sum of weights,// with total * weight inside std::int64_t; split_expense checks all of// that before calling it.[[nodiscard]] std::vector<Money> allocate(Money total, const std::vector<std::int64_t>& weights);VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
std::vector<Money> allocate(Money total, const std::vector<std::int64_t>& weights) { const std::int64_t weight_sum = std::accumulate(weights.begin(), weights.end(), std::int64_t{0}); if (weight_sum <= 0) throw std::invalid_argument("allocate needs a positive sum of weights");
std::vector<Money> parts(weights.size()); // lost[i] is the fraction of a cent that rounding down took from part // i, counted in 1/weight_sum of a cent, so it is an exact integer. std::vector<std::int64_t> lost(weights.size()); std::int64_t given = 0; for (std::size_t i = 0; i < weights.size(); ++i) { const std::int64_t scaled = total.cents * weights[i]; parts[i] = cents(scaled / weight_sum); // integer division rounds down here (all >= 0) lost[i] = scaled % weight_sum; given += parts[i].cents; }
// Put the part indices in order of most lost first. stable_sort keeps // equal losses in list order, which is the tie rule: earlier wins. std::vector<std::size_t> order(weights.size()); std::iota(order.begin(), order.end(), std::size_t{0}); // 0, 1, 2, ... std::stable_sort(order.begin(), order.end(), [&lost](std::size_t a, std::size_t b) { return lost[a] > lost[b]; });
// The losses add up to exactly (total - given) whole cents, and each // is under one cent, so fewer cents are left than there are parts. A // part with weight 0 lost nothing, so it never gets one: there are // always more parts that lost something than cents to give out. const auto left_over = static_cast<std::size_t>(total.cents - given); for (std::size_t k = 0; k < left_over; ++k) parts[order[k]].cents += 1; return parts;}The rule is known as the largest remainder method. Each part first gets its exact share rounded down. Rounding down can only take away, so some cents may be left over, always fewer than the number of parts. Those go one each to the parts that lost the most by rounding down, and a tie goes to the part listed first.
How this code works: allocate on the demo's groceries
The step 1 demo splits 45.67 (4,567 cents) at 50%, 25%, and 25% among
Asha, Ben, and Dana. The weights are 50, 25, 25, so weight_sum is
100.
| Part | Weight | scaled = 4567 × weight |
parts[i] = scaled / 100 |
lost[i] = scaled % 100 |
|---|---|---|---|---|
| Asha | 50 | 228,350 | 2,283 | 50 |
| Ben | 25 | 114,175 | 1,141 | 75 |
| Dana | 25 | 114,175 | 1,141 | 75 |
- Round everything down.
givenis 2,283 + 1,141 + 1,141 = 4,565, so 2 cents are left over. - Read the losses.
lost[i]is in hundredths of a cent here (1/weight_sumof a cent): Asha lost 0.50 of a cent, Ben and Dana 0.75 each. They are whole numbers, so comparing them is exact. - Order by loss.
orderstarts as 0, 1, 2 (std::iotafills in the counting numbers).stable_sortwith “more lost first” gives 1, 2, 0: Ben and Dana tie at 75 and keep their list order, then Asha. - Hand out the 2 cents to
order[0]andorder[1]: Ben and Dana.
The shares are 22.83, 11.42, 11.42, which is what the demo prints, and they add up to 45.67. Asha’s exact share was 22.835 and she pays 22.83; Ben’s was 11.4175 and he pays 11.42. Nobody is more than a cent from their exact share, and here the two who were rounded down furthest are the ones who pay the extra cent.
For the taxi, 10.00 among three, every part’s scaled is 1,000, every
part is 333 and every lost is 1. One cent is left, all three tie, so
stable_sort leaves them in list order and the cent goes to the first
listed, Asha: 3.34, 3.33, 3.33.
Why this rule, and not “the payer absorbs it” or “the last person pays the rest”?
- It is fair to within a cent (INV-2). Each part is its exact share rounded down, or one cent more, and so never further than one cent from it. “The last person pays the rest” can put several cents on one person: 0.13 among seven is 0.01 each for six people and 0.07 for the last, about five cents more than a fair share of 0.0186. “The payer absorbs it” has the same problem, and no answer at all when the payer is not one of the people sharing the expense.
- It adds up exactly (INV-1). The losses add up to the cents left over, so handing those out gives back exactly the total.
- It is repeatable (INV-5). Integer arithmetic, a stable sort, and the list order as the tie rule: nothing depends on memory, hash order, or chance. The person typing the expense chooses the list order, so the tie rule is visible to them.
- It is one rule for every split. Equal and percent share the same code, and so do future rules that can be written as weights.
Property-based and table-driven tests builds the same rule from its properties and tests them one by one; here it is one function that the rest of the program can rely on.
Checking an expense
Section titled “Checking an expense”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
SplitResult split_expense(const Expense& expense, const std::vector<MemberId>& members) { // 1. Checks that do not depend on the kind of split. Each returns at // the first problem, so the user hears about one thing at a time. if (expense.amount <= Money{}) { return reject(Reason::amount_not_positive, "The amount must be more than zero."); } if (expense.amount > max_amount) { return reject(Reason::amount_too_large, "The amount is over " + to_string(max_amount) + "."); } if (!is_member(members, expense.paid_by)) { return reject(Reason::unknown_member, expense.paid_by + " is not in the group."); } const std::vector<MemberId> names = named_in(expense.split); if (names.empty()) return reject(Reason::empty_split, "Nobody shares this expense."); for (std::size_t i = 0; i < names.size(); ++i) { if (!is_member(members, names[i])) { return reject(Reason::unknown_member, names[i] + " is not in the group."); } // A name seen earlier in the list: the split would be ambiguous. if (std::find(names.begin(), names.begin() + static_cast<std::ptrdiff_t>(i), names[i]) != names.begin() + static_cast<std::ptrdiff_t>(i)) { return reject(Reason::duplicate_member, names[i] + " is listed twice."); } }
// 2. The rule for each kind of split turns it into one weight per name. std::vector<std::int64_t> weights; if (std::holds_alternative<Equal>(expense.split)) { weights.assign(names.size(), 1); // everyone weighs the same } else if (const auto* exact = std::get_if<Exact>(&expense.split)) { for (const auto& [member, part] : exact->parts) { if (part < Money{}) return reject(Reason::negative_part, member + "'s part is negative."); weights.push_back(part.cents); } if (!adds_up_to(weights, expense.amount.cents)) { return reject(Reason::exact_sum_mismatch, "The parts must add up to " + to_string(expense.amount) + "."); } // Exact parts need no rounding: each person owes what was typed. Shares shares; for (const auto& [member, part] : exact->parts) shares.push_back({member, part}); return shares; } else if (const auto* percent = std::get_if<Percent>(&expense.split)) { for (const auto& [member, share] : percent->parts) { if (share < 0) return reject(Reason::negative_part, member + "'s percent is negative."); weights.push_back(share); } if (!adds_up_to(weights, 100)) { return reject(Reason::percent_sum_mismatch, "The percents must add up to 100."); } }
// 3. Equal and percent splits share out the cents by the one rounding // rule in allocate, so the shares add up to the amount exactly. const std::vector<Money> parts = allocate(expense.amount, weights); Shares shares; for (std::size_t i = 0; i < names.size(); ++i) shares.push_back({names[i], parts[i]}); return shares;}split_expense is pure: it reads the expense and the member list and
returns a value. It changes nothing, and it holds no state, so the same
call always gives the same answer.
How this code works: The order of the checks in split_expense
- Checks that do not depend on the kind of split. The amount is
more than zero and at most
max_amount; the payer is a member.named_inthen gets the names the split mentions, whatever its kind, usingstd::get_if, which returns a pointer to the alternative the variant holds, ornullptrif it holds another. - Checks on the names. Not empty; each one a member; none twice.
The duplicate check looks for the name among the names before
it (
names.begin()up to positioni), so it fires at the second appearance of a name. Thestatic_cast<std::ptrdiff_t>is there because an iterator moves by a signed distance andiis unsigned. - The rule of each kind becomes weights.
std::holds_alternativeasks which kind it is. Equal: one weight per name, all 1. Exact: each part must be zero or more, andadds_up_tochecks that they add up to the amount; then the shares are the parts as typed, with no rounding at all, and the function returns early. Percent: each must be zero or more, and they must add up to 100. - Share out by
allocate, and pair each part with its name, in the order of the split.
adds_up_to compares each value with what is left before
subtracting it. That is how ac_3_2 can pass a part of
INT64_MAX cents and get a plain “the parts do not add up”: adding
the parts first would overflow. Each check returns at the first
problem, so the person hears about one thing at a time.
A split of 10.00 with a part of 15.00 and a part of −5.00 adds up, and
is still refused as negative_part: someone would be paid by the
expense instead of owing it, and that is a transfer, not a share.
The group
Section titled “The group”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Money handed from one member to another to pay back what they owe.struct Transfer { MemberId from; MemberId to; Money amount; friend bool operator==(const Transfer&, const Transfer&) = default;};
// Each member's net position. Positive: the group owes them. Negative:// they owe the group. A std::map keeps the members sorted by name, so// anything that walks the balances does so in the same order every run.using Balances = std::map<MemberId, Money>;
// A group of people who share expenses. It owns its member list and the// balances, both plain values. It keeps balances, not a list of past// expenses, because nothing in this step needs the history.//// Invariant: the balances add up to exactly zero. Every change it makes// adds to one member exactly what it takes from others, and a change it// refuses touches nothing.class Group {public: // Throws std::invalid_argument for an empty list, an empty name, or a // name listed twice: a group set up wrong is a bug in the caller, not // something a user typed into one expense. explicit Group(std::vector<MemberId> members);
[[nodiscard]] const std::vector<MemberId>& members() const { return members_; } [[nodiscard]] const Balances& balances() const { return balances_; }
// Splits the expense, credits the payer with the whole amount, and // debits each person their share. Returns the shares, or the // rejection and leaves the balances as they were. [[nodiscard]] SplitResult add_expense(const Expense& expense);
// Records money paid back. Returns no value when it is accepted, or // the reason it was refused: an unknown member, paying oneself, or an // amount that is not positive or is over max_amount. [[nodiscard]] std::optional<Rejection> record_transfer(const Transfer& transfer);
private: std::vector<MemberId> members_; Balances balances_;};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
SplitResult Group::add_expense(const Expense& expense) { SplitResult result = split_expense(expense, members_); // Refused: return the rejection before anything is changed. if (std::holds_alternative<Rejection>(result)) return result;
// The shares add up to the amount (split_expense promises it), so the // credit and the debits cancel out and the balances still sum to zero. balances_[expense.paid_by] += expense.amount; for (const Share& share : std::get<Shares>(result)) balances_[share.member] -= share.amount; return result;}add_expense is three lines because split_expense did the work. It
is also where INV-3 and INV-4 meet:
- All or nothing. The rejection returns before the first balance changes. There is no half-applied expense to undo.
- Zero-sum. The payer is credited the whole amount, and each member is debited their share. INV-1 says the shares add up to the amount, so the credit and the debits cancel, and the sum of balances is unchanged: zero before, zero after.
record_transfer follows the same pattern: five checks, then one
credit and one debit of the same amount. A member who pays back 5.00
has their balance go up by 5.00 (they owe 5.00 less), and the
receiver’s goes down by 5.00.
The balances are a std::map, sorted by name, not an
std::unordered_map. Everything that walks the balances (printing,
settle_up) then does so in the same order on every run and every
machine, which INV-5 needs.
Settling up
Section titled “Settling up”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Suggests transfers that bring every balance to zero, using the greedy// rule: the member who owes the most pays the member owed the most as// much as settles one of them, and that repeats. Each transfer settles at// least one member, so n members need at most n - 1 transfers.//// Greedy is fast and usually good, but not always the fewest: when the// group splits into smaller sets whose balances add up to zero on their// own, settling each set apart can need fewer. Finding the true minimum// is NP-hard in general, so the suggestion is "few", not "fewest".//// Ties go to the member whose name sorts first. Throws// std::invalid_argument if the balances do not add up to zero.[[nodiscard]] std::vector<Transfer> settle_up(const Balances& balances);VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
std::vector<Transfer> settle_up(const Balances& balances) { if (sum_of(balances) != Money{}) throw std::invalid_argument("balances must add up to zero");
Balances left = balances; // a copy: the suggestion changes nothing real std::vector<Transfer> plan; while (true) { // Find the largest creditor and the largest debtor. The map walks // names in sorted order and only a strictly larger amount replaces // the one found, so on a tie the first name wins. auto creditor = left.end(); auto debtor = left.end(); for (auto it = left.begin(); it != left.end(); ++it) { const Money balance = it->second; if (balance > Money{} && (creditor == left.end() || balance > creditor->second)) { creditor = it; } if (balance < Money{} && (debtor == left.end() || balance < debtor->second)) { debtor = it; } } // The balances add up to zero, so if nobody is owed, nobody owes. if (creditor == left.end()) break;
// Pay as much as settles the smaller of the two; that one is now // at zero, and the other is closer to it. const Money amount = std::min(creditor->second, -debtor->second); plan.push_back({debtor->first, creditor->first, amount}); creditor->second -= amount; debtor->second += amount; } return plan;}How this code works: settle_up on the step 1 demo's balances
After the four accepted expenses, the balances are Asha −51.17, Ben
−129.75, Chen 221.67, Dana −40.75. They add up to zero, so the first
check passes, and left is a copy to work on.
| Round | Largest creditor | Largest debtor | amount (the smaller) |
Transfer | left afterwards |
|---|---|---|---|---|---|
| 1 | Chen 221.67 | Ben −129.75 | 129.75 | Ben pays Chen 129.75 | Asha −51.17, Ben 0.00, Chen 91.92, Dana −40.75 |
| 2 | Chen 91.92 | Asha −51.17 | 51.17 | Asha pays Chen 51.17 | Asha 0.00, Ben 0.00, Chen 40.75, Dana −40.75 |
| 3 | Chen 40.75 | Dana −40.75 | 40.75 | Dana pays Chen 40.75 | all 0.00 |
| 4 | none | none | the loop ends |
- Find the two ends. One pass over the map finds the largest positive balance and the most negative one. Only a strictly larger amount replaces the one found, and the map walks names in order, so a tie goes to the name that sorts first.
- Pay as much as settles one of them.
std::min(creditor, -debtor)is the amount that brings the smaller of the two to exactly zero. The other moves closer to zero without passing it. - Stop when nobody is owed. The balances add up to zero, so when no balance is positive, none is negative either.
Every round brings at least one member to zero, and the last round brings two, so four members need at most three transfers. The loop ends because each round leaves one more member at zero.
Where each rule lives
Section titled “Where each rule lives”| Rule | Where it lives |
|---|---|
| Money is whole cents, and how big an amount may be | Money, max_amount |
| Which kinds of split exist, and what data each needs | the Split variant |
| What makes an expense valid | split_expense, and nowhere else |
| How cents left over are shared out | allocate, and nowhere else |
| That an expense changes balances all or nothing | Group::add_expense |
| That the balances add up to zero | Group: every change credits what it debits |
| What makes a transfer valid | Group::record_transfer |
| Who pays whom to settle up | settle_up |
| Repeatable order | list order in a split, stable_sort, the sorted map |
Verification trace
Section titled “Verification trace”Take the taxi in the step 1 demo: Ben pays 10.00, split equally among Asha, Ben, and Chen.
Text description of the diagram
The caller asks the group to add the taxi: Ben paid 10.00, split equally among Asha, Ben, and Chen. The group passes the expense and its member list to split_expense, which checks that the amount is positive and under the cap, that Ben is a member, and that every name in the split is known and listed once. It calls allocate with 1,000 cents and weights 1, 1, 1. Allocate gives 333 to each, finds one cent left over and a three-way tie, and gives the cent to the first listed, returning 334, 333, 333. Split_expense returns the shares Asha 3.34, Ben 3.33, Chen 3.33. Only now does the group change: Ben is credited 10.00, and each share is debited from its member. The group returns the same shares to the caller.
Diagram source (Mermaid)
sequenceDiagram
participant U as caller
participant G as Group
participant S as split_expense
participant A as allocate
U->>G: add_expense(Taxi, Ben, 10.00, Equal Asha Ben Chen)
G->>S: split_expense(expense, members_)
Note over S: amount positive, under the cap
Note over S: Ben is a member, names known, none twice
S->>A: allocate(1000 cents, weights 1 1 1)
Note over A: 333 each, 1 cent left, all tie
A-->>S: 334, 333, 333
S-->>G: Shares Asha 3.34, Ben 3.33, Chen 3.33
Note over G: Ben +10.00, then each share debited
G-->>U: the same SharesStep by step, in the code, starting from the balances after dinner (Asha 75.00, Ben −25.00, Chen −25.00, Dana −25.00):
split_expensepasses every check in steps 1 to 3 of the walkthrough above and builds weights 1, 1, 1.allocate(cents(1000), {1, 1, 1})returns 334, 333, 333, as traced above.add_expenseseesShares, notRejection, and credits Ben 10.00: Ben is at −15.00.- It debits Asha 3.34 (to 71.66), Ben 3.33 (to −18.33), and Chen 3.33 (to −28.33). Dana is unchanged at −25.00.
- The sum: 71.66 − 18.33 − 28.33 − 25.00 = 0.00.
Now put a refusal at each step instead. The Museum expense in the demo
fails in step 3 of the walkthrough (exact parts of 20.00 and 15.00 for
40.00), and the Boat fails in step 1 (Eve is not a member). Both return
a Rejection before add_expense reaches its first +=, so the
balances printed after them are exactly the balances before them.
Architecture and patterns
Section titled “Architecture and patterns”Money as a number of cents
Section titled “Money as a number of cents”A split as a variant
Section titled “A split as a variant”Why not a Strategy hierarchy? The textbook answer for “several ways
to do one thing” is the Strategy pattern: a
SplitRule interface and a class per rule.
IllustrativeA fragment for explanation; not compiled on its own.
// Illustrative: the three rules as a Strategy hierarchy (not the design// chosen here).class SplitRule {public: virtual ~SplitRule() = default; // Each rule checks its own data and shares out the amount. [[nodiscard]] virtual SplitResult split(Money amount, const std::vector<MemberId>& members) const = 0;};
// An expense would hold its rule by pointer, so it no longer copies as// a plain value: copying it needs a clone function on every rule.struct RuleExpense { MemberId paid_by; Money amount; std::unique_ptr<SplitRule> rule;};It works, and it is the wrong trade here, for four reasons:
- The set is closed. The group named three rules, and all three live in this file. Strategy pays for itself when new rules are added by code that cannot edit this file, such as a plug-in, and that is not this program.
- Most of the checking is shared. Every rule needs the same name
checks (known, not empty, nobody twice). With a hierarchy, each
class repeats them or calls a helper; with a variant,
split_expensedoes them once, and only the part that differs is per kind. - The rules are data, not behaviour. What differs between them is
the numbers they hold; the behaviour is the same
allocatefor all butExact. A variant holds data; a hierarchy is for behaviour. - A value is simpler. An
Expensewith a variant copies and moves like any value, with nounique_ptrto own and no virtual calls. With a hierarchy, copying an expense needs aclonefunction.
The design’s real extension point is quieter: a rule turns into
weights, and allocate does the rest. A new rule such as “by nights
stayed” is a new alternative and one more branch that makes weights;
the Exercise adds it. If the group later wanted rules
chosen at run time from a list that other teams maintain, a
SplitRule interface would earn its place, and allocate would stay
as it is, called by every rule. See
When to use Strategy, and when not to.
Where the balances live
Section titled “Where the balances live”What the group gives up: it cannot say “Asha owes Ben for the taxi”, because it keeps no history. That was not asked for, and adding a list of expenses later does not change the balances or the invariant; see Production limitations.
Greedy settle-up, honestly
Section titled “Greedy settle-up, honestly”The greedy rule is simple, quick, and makes at most n − 1 transfers for
n members, which the group asked for: “few is good”. It is not
always the fewest. ac_7_3 has the smallest kind of case where it
loses:
| Member | Balance |
|---|---|
| Asha | +6.00 |
| Ben | +5.00 |
| Chen | −3.00 |
| Dana | −3.00 |
| Eli | −5.00 |
Greedy pays the largest creditor, Asha, from the largest debtor, Eli, first:
| Round | Transfer | Left |
|---|---|---|
| 1 | Eli pays Asha 5.00 | Asha +1, Ben +5, Chen −3, Dana −3, Eli 0 |
| 2 | Chen pays Ben 3.00 | Asha +1, Ben +2, Chen 0, Dana −3 |
| 3 | Dana pays Ben 2.00 | Asha +1, Ben 0, Dana −1 |
| 4 | Dana pays Asha 1.00 | all zero |
In round 2, Chen and Dana tie at −3.00, and Chen sorts first. But the group is really two groups that each add up to zero on their own: Asha, Chen, and Dana (+6 − 3 − 3) and Ben and Eli (+5 − 5). Settled apart, that is three transfers: Chen pays Asha 3.00, Dana pays Asha 3.00, Eli pays Ben 5.00. The test checks that greedy makes four, and that these three really do settle everyone.
In general, the fewest transfers is the number of members with a non-zero balance, less the largest number of separate sets they can be split into that each add up to zero. Finding that largest number is a search over subsets, and the problem is NP-hard in general, which is why the code does not try. For a group of a dozen people an exact search would be fast enough, and it is a fair extension; the point is to choose it on purpose and to say which one the program does.
What is not here, and why
Section titled “What is not here, and why”- No Strategy classes. A variant, for the reasons above.
- No
Memberclass. A name and a balance are all a member is in this model. A class with nothing to protect would be ceremony. - No exceptions for a user’s mistakes. A refused expense is a
Rejection. The only exceptions are for a group set up wrong, forsettle_upgiven balances that do not add up, and forallocatecalled with no positive weight, all of them programming errors. - No history and no undo. Not asked for; the balances are enough.
- No thread, no storage. One caller, in memory (NFR-5).
Building it step by step
Section titled “Building it step by step”The example has two steps, each a complete program with its own tests:
- Step 1 is the design above: a group, the three splits, the rounding rule, validation, balances, and settling up.
- Step 2 is the change: expenses in several currencies at fixed rates. See When the requirements change.
The order inside step 1 is worth copying. Money came first, then
allocate alone with its property test (ac_6_2), because every
later test relies on it. Then the equal split, then exact, then
percent, each with its refusals. Then the Group and the zero-sum
random test, and last settle_up, with the case where greedy loses
written down as a test so that nobody later “fixes” it into a claim it
cannot keep.
Scenarios
Section titled “Scenarios”The step 1 demo
Section titled “The step 1 demo”The demo is a weekend away: four expenses, one of each kind and one that leaves cents over, two refusals, the balances, and the plan.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
Group trip({"Asha", "Ben", "Chen", "Dana"});
add(trip, {"Dinner", "Asha", units(100), Equal{{"Asha", "Ben", "Chen", "Dana"}}});// 10.00 / 3 leaves one cent over; Asha is listed first, so Asha pays it.add(trip, {"Taxi", "Ben", units(10), Equal{{"Asha", "Ben", "Chen"}}});add(trip, {"Hotel", "Chen", units(300), Exact{{{"Asha", units(100)}, {"Ben", units(100)}, {"Chen", units(50)}, {"Dana", units(50)}}}});// 25% of 45.67 is 11.4175: Ben and Dana lose more by rounding down// than Asha does, so the two spare cents go to them.add(trip, {"Groceries", "Dana", cents(4567), Percent{{{"Asha", 50}, {"Ben", 25}, {"Dana", 25}}}});
add(trip, {"Museum", "Asha", units(40), Exact{{{"Asha", units(20)}, {"Ben", units(15)}}}});add(trip, {"Boat", "Eve", units(60), Equal{{"Asha", "Eve"}}});show(trip);
std::cout << "Settle up:\n";for (const Transfer& transfer : settle_up(trip.balances())) { std::cout << " " << transfer.from << " pays " << transfer.to << " " << to_string(transfer.amount) << "\n"; static_cast<void>(trip.record_transfer(transfer)); // accepted: it came from the plan}show(trip);Dinner (100.00, paid by Asha): Asha 25.00, Ben 25.00, Chen 25.00, Dana 25.00Taxi (10.00, paid by Ben): Asha 3.34, Ben 3.33, Chen 3.33Hotel (300.00, paid by Chen): Asha 100.00, Ben 100.00, Chen 50.00, Dana 50.00Groceries (45.67, paid by Dana): Asha 22.83, Ben 11.42, Dana 11.42Museum (40.00, paid by Asha): refused, exact parts do not add up. The parts must add up to 40.00.Boat (60.00, paid by Eve): refused, unknown member. Eve is not in the group.Balances: Asha -51.17 Ben -129.75 Chen 221.67 Dana -40.75 (sum 0.00)Settle up: Ben pays Chen 129.75 Asha pays Chen 51.17 Dana pays Chen 40.75Balances: Asha 0.00 Ben 0.00 Chen 0.00 Dana 0.00 (sum 0.00)Read the output against the rules:
- Dinner, 100.00 among four, divides evenly: 25.00 each.
- Taxi, 10.00 among three, leaves one cent over; all three lost the same, so the first listed, Asha, pays 3.34.
- Hotel is exact parts, owed as typed, with no rounding.
- Groceries, 45.67 at 50/25/25, leaves two cents over. Ben and Dana lost more by rounding down than Asha, so they pay 11.42 each.
- Museum is refused: 20.00 and 15.00 do not make 40.00.
- Boat is refused: Eve is not in the group. The balances after both refusals are the same as before them.
- The balances add up to 0.00, and the plan has three transfers, all to Chen, who paid the hotel. After they are recorded, everyone is at 0.00.
The tests are named after the acceptance criteria and run against the
real Group, split_expense, allocate, and settle_up. Two helpers
keep them short: shares_of adds an expense that must be accepted and
returns its shares, and refusal_of adds one that must be refused,
checks that the balances did not change, and returns the reason.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
LLD_TEST(ac_1_1_a_group_starts_with_every_member_at_zero) { const Group group(four); LLD_CHECK_EQ(group.balances().size(), std::size_t{4}); for (const auto& [member, balance] : group.balances()) LLD_CHECK_EQ(balance, Money{});}
LLD_TEST(ac_1_2_a_group_set_up_wrong_is_refused) { LLD_CHECK_THROWS(Group({}), std::invalid_argument); LLD_CHECK_THROWS(Group({"Asha", ""}), std::invalid_argument); LLD_CHECK_THROWS(Group({"Asha", "Ben", "Asha"}), std::invalid_argument);}
LLD_TEST(ac_2_1_an_equal_split_that_divides_evenly) { Group group(four); const Shares shares = shares_of(group, {"Dinner", "Asha", units(100), Equal{four}}); LLD_CHECK_EQ(shares, (Shares{{"Asha", units(25)}, {"Ben", units(25)}, {"Chen", units(25)}, {"Dana", units(25)}})); LLD_CHECK_EQ(group.balances().at("Asha"), units(75)); LLD_CHECK_EQ(group.balances().at("Ben"), units(-25));}
LLD_TEST(ac_2_2_left_over_cents_go_to_the_first_members_listed) { Group group(four); // 1000 / 3 = 333 rest 1; 1001 / 3 = 333 rest 2. LLD_CHECK_EQ(shares_of(group, {"Taxi", "Ben", cents(1000), Equal{{"Chen", "Asha", "Ben"}}}), (Shares{{"Chen", cents(334)}, {"Asha", cents(333)}, {"Ben", cents(333)}})); LLD_CHECK_EQ(shares_of(group, {"Taxi", "Ben", cents(1001), Equal{{"Chen", "Asha", "Ben"}}}), (Shares{{"Chen", cents(334)}, {"Asha", cents(334)}, {"Ben", cents(333)}}));}
LLD_TEST(ac_2_3_the_same_expense_always_splits_the_same_way) { Group a(four); Group b(four); const Expense taxi{"Taxi", "Ben", cents(1001), Equal{{"Dana", "Ben", "Chen"}}}; LLD_CHECK_EQ(shares_of(a, taxi), shares_of(b, taxi)); LLD_CHECK(a.balances() == b.balances());}
LLD_TEST(ac_2_4_one_cent_among_many_goes_to_the_first) { Group group(four); LLD_CHECK_EQ(shares_of(group, {"Sweet", "Asha", cents(1), Equal{four}}), (Shares{{"Asha", cents(1)}, {"Ben", cents(0)}, {"Chen", cents(0)}, {"Dana", cents(0)}}));}
LLD_TEST(ac_3_1_exact_parts_are_owed_as_typed) { Group group(four); const Shares parts{{"Asha", cents(10001)}, {"Ben", cents(0)}, {"Dana", cents(19999)}}; LLD_CHECK_EQ(shares_of(group, {"Hotel", "Chen", units(300), Exact{{{"Asha", cents(10001)}, {"Ben", cents(0)}, {"Dana", cents(19999)}}}}), parts); LLD_CHECK_EQ(group.balances().at("Chen"), units(300));}
LLD_TEST(ac_3_2_exact_parts_must_add_up_to_the_amount) { Group group(four); LLD_CHECK_EQ(refusal_of(group, {"Hotel", "Chen", units(300), Exact{{{"Asha", units(100)}, {"Ben", units(199)}}}}), std::optional{Reason::exact_sum_mismatch}); LLD_CHECK_EQ(refusal_of(group, {"Hotel", "Chen", units(300), Exact{{{"Asha", units(100)}, {"Ben", units(201)}}}}), std::optional{Reason::exact_sum_mismatch}); // The amount is reached by the first part, and a later one is extra. LLD_CHECK_EQ(refusal_of(group, {"Hotel", "Chen", units(300), Exact{{{"Asha", units(300)}, {"Ben", cents(1)}}}}), std::optional{Reason::exact_sum_mismatch}); // A part so big that adding it would overflow is still just "too much". LLD_CHECK_EQ(refusal_of(group, {"Hotel", "Chen", units(300), Exact{{{"Asha", units(100)}, {"Ben", cents(INT64_MAX)}}}}), std::optional{Reason::exact_sum_mismatch});}
LLD_TEST(ac_3_3_a_negative_exact_part_is_refused) { Group group(four); LLD_CHECK_EQ(refusal_of(group, {"Hotel", "Chen", units(300), Exact{{{"Asha", units(310)}, {"Ben", units(-10)}}}}), std::optional{Reason::negative_part}); // One cent below zero is refused too, even with the sum made to fit. LLD_CHECK_EQ(refusal_of(group, {"Hotel", "Chen", units(300), Exact{{{"Asha", cents(30001)}, {"Ben", cents(-1)}}}}), std::optional{Reason::negative_part});}
LLD_TEST(ac_4_1_a_percent_split_that_divides_evenly) { Group group(four); LLD_CHECK_EQ(shares_of(group, {"Car", "Dana", units(200), Percent{{{"Asha", 50}, {"Ben", 30}, {"Dana", 20}}}}), (Shares{{"Asha", units(100)}, {"Ben", units(60)}, {"Dana", units(40)}}));}
LLD_TEST(ac_4_2_percents_must_add_up_to_100) { Group group(four); LLD_CHECK_EQ(refusal_of(group, {"Car", "Dana", units(200), Percent{{{"Asha", 50}, {"Ben", 49}}}}), std::optional{Reason::percent_sum_mismatch}); LLD_CHECK_EQ(refusal_of(group, {"Car", "Dana", units(200), Percent{{{"Asha", 50}, {"Ben", 51}}}}), std::optional{Reason::percent_sum_mismatch}); LLD_CHECK_EQ(refusal_of(group, {"Car", "Dana", units(200), Percent{{{"Asha", 100}, {"Ben", 1}}}}), std::optional{Reason::percent_sum_mismatch}); LLD_CHECK_EQ(refusal_of(group, {"Car", "Dana", units(200), Percent{{{"Asha", 110}, {"Ben", -10}}}}), std::optional{Reason::negative_part}); LLD_CHECK_EQ(refusal_of(group, {"Car", "Dana", units(200), Percent{{{"Asha", 101}, {"Ben", -1}}}}), std::optional{Reason::negative_part});}
LLD_TEST(ac_4_3_a_spare_cent_goes_to_whoever_rounding_cost_most) { Group group(four); // 75% of 3 cents is 2.25 and 25% is 0.75. Rounding down costs Ben // 0.75, so Ben gets the spare cent, not Asha who is listed first. LLD_CHECK_EQ(shares_of(group, {"Gum", "Dana", cents(3), Percent{{{"Asha", 75}, {"Ben", 25}}}}), (Shares{{"Asha", cents(2)}, {"Ben", cents(1)}})); // 45.67 at 50/25/25: 22.835, 11.4175, 11.4175. Ben and Dana lose more // (0.75 of a cent) than Asha (0.5), and they tie: both get a cent. LLD_CHECK_EQ(shares_of(group, {"Food", "Dana", cents(4567), Percent{{{"Asha", 50}, {"Ben", 25}, {"Dana", 25}}}}), (Shares{{"Asha", cents(2283)}, {"Ben", cents(1142)}, {"Dana", cents(1142)}}));}
LLD_TEST(ac_4_4_equal_losses_give_the_cent_to_the_one_listed_first) { Group group(four); // 1 cent at 50/50: both lose half a cent; the first listed pays it. LLD_CHECK_EQ(shares_of(group, {"Gum", "Asha", cents(1), Percent{{{"Ben", 50}, {"Asha", 50}}}}), (Shares{{"Ben", cents(1)}, {"Asha", cents(0)}}));}
LLD_TEST(ac_4_5_a_zero_percent_member_never_gets_a_cent) { Group group(four); LLD_CHECK_EQ(shares_of(group, {"Gum", "Asha", cents(2), Percent{{{"Ben", 0}, {"Asha", 50}, {"Chen", 50}}}}), (Shares{{"Ben", cents(0)}, {"Asha", cents(1)}, {"Chen", cents(1)}})); LLD_CHECK_EQ(shares_of(group, {"Gum", "Asha", cents(1), Percent{{{"Ben", 0}, {"Asha", 100}}}}), (Shares{{"Ben", cents(0)}, {"Asha", cents(1)}}));}Most of these tests pin down a cent. ac_4_3 is the one that tells the
rounding rule apart from a simpler one: 3 cents at 75% and 25% gives
2.25 and 0.75, and the spare cent goes to Ben, who lost 0.75 by
rounding down, not to Asha, who is listed first and lost 0.25. A rule
of “spare cents to the first listed” would pass ac_2_2 and fail here.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
LLD_TEST(ac_5_1_the_amount_must_be_positive_and_not_too_large) { Group group(four); LLD_CHECK_EQ(refusal_of(group, {"Free", "Asha", cents(0), Equal{four}}), std::optional{Reason::amount_not_positive}); LLD_CHECK_EQ(refusal_of(group, {"Refund", "Asha", cents(-500), Equal{four}}), std::optional{Reason::amount_not_positive}); LLD_CHECK_EQ(refusal_of(group, {"Yacht", "Asha", max_amount + cents(1), Equal{four}}), std::optional{Reason::amount_too_large}); // The largest amount is accepted, with exact parts as big as it is. const Shares big = shares_of(group, {"House", "Asha", max_amount, Exact{{{"Ben", max_amount}, {"Chen", Money{}}}}}); LLD_CHECK_EQ(big.at(0).amount, max_amount);}
LLD_TEST(ac_5_2_everyone_named_must_be_in_the_group) { Group group(four); LLD_CHECK_EQ(refusal_of(group, {"Boat", "Eve", units(60), Equal{four}}), std::optional{Reason::unknown_member}); LLD_CHECK_EQ(refusal_of(group, {"Boat", "Asha", units(60), Equal{{"Asha", "Eve"}}}), std::optional{Reason::unknown_member}); LLD_CHECK_EQ(refusal_of(group, {"Boat", "Asha", units(60), Exact{{{"Eve", units(60)}}}}), std::optional{Reason::unknown_member}); LLD_CHECK_EQ(refusal_of(group, {"Boat", "Asha", units(60), Percent{{{"Eve", 100}}}}), std::optional{Reason::unknown_member});}
LLD_TEST(ac_5_3_a_split_must_name_someone_and_nobody_twice) { Group group(four); LLD_CHECK_EQ(refusal_of(group, {"Boat", "Asha", units(60), Equal{}}), std::optional{Reason::empty_split}); LLD_CHECK_EQ(refusal_of(group, {"Boat", "Asha", units(60), Exact{}}), std::optional{Reason::empty_split}); LLD_CHECK_EQ(refusal_of(group, {"Boat", "Asha", units(60), Percent{}}), std::optional{Reason::empty_split}); LLD_CHECK_EQ(refusal_of(group, {"Boat", "Asha", units(60), Equal{{"Ben", "Chen", "Ben"}}}), std::optional{Reason::duplicate_member}); LLD_CHECK_EQ(refusal_of(group, {"Boat", "Asha", units(60), Percent{{{"Ben", 50}, {"Ben", 50}}}}), std::optional{Reason::duplicate_member});}
LLD_TEST(ac_5_4_the_payer_need_not_share_the_expense) { Group group(four); static_cast<void>(shares_of(group, {"Gift", "Asha", units(30), Equal{{"Ben", "Chen", "Dana"}}})); LLD_CHECK_EQ(group.balances().at("Asha"), units(30)); LLD_CHECK_EQ(group.balances().at("Dana"), units(-10));}Every refusal goes through refusal_of, so every one of them also
checks INV-4, that the refusal changed no balance.
The invariant, against random expenses.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The key invariant, against many random expenses, some of them invalid:// every split's shares add up to its amount, and the balances add up to// zero after every expense and transfer, accepted or refused. The seed is// fixed, so a failure happens again on the next run.LLD_TEST(ac_6_1_balances_always_add_up_to_zero) { const std::vector<MemberId> people = {"Asha", "Ben", "Chen", "Dana", "Eli", "Fay", "Gus"}; Group group(people); std::mt19937 random(2026); auto pick = [&random](std::int64_t low, std::int64_t high) { return std::uniform_int_distribution<std::int64_t>(low, high)(random); }; int accepted = 0; for (int round = 0; round < 3000; ++round) { // Pick a payer (sometimes a stranger) and some of the members. const MemberId payer = pick(0, 20) == 0 ? "Zed" : people[static_cast<std::size_t>(pick(0, 6))]; std::vector<MemberId> among; for (const MemberId& person : people) { if (pick(0, 1) == 1) among.push_back(person); } const Money amount = cents(pick(-2, 100'000)); Split split = Equal{among}; if (round % 3 == 1) { // exact parts: random, then the last fixed up (mostly) Exact exact; Money left = amount; for (const MemberId& person : among) { const Money part = cents(pick(0, left.cents > 0 ? left.cents : 0)); exact.parts.emplace_back(person, part); left -= part; } if (!exact.parts.empty() && pick(0, 9) != 0) exact.parts.back().second += left; split = exact; } else if (round % 3 == 2) { // percents: the same idea out of 100 Percent percent; int left = 100; for (const MemberId& person : among) { const int share = static_cast<int>(pick(0, left)); percent.parts.emplace_back(person, share); left -= share; } if (!percent.parts.empty() && pick(0, 9) != 0) percent.parts.back().second += left; split = percent; } const SplitResult result = group.add_expense({"random", payer, amount, split}); if (const auto* shares = std::get_if<Shares>(&result)) { ++accepted; Money sum; for (const Share& share : *shares) sum += share.amount; LLD_CHECK_EQ(sum, amount); } LLD_CHECK_EQ(sum_of(group.balances()), Money{});
if (round % 10 == 0) { // now and then, someone pays someone back static_cast<void>(group.record_transfer({people[static_cast<std::size_t>(pick(0, 6))], people[static_cast<std::size_t>(pick(0, 6))], cents(pick(-1, 5'000))})); LLD_CHECK_EQ(sum_of(group.balances()), Money{}); } } // Most rounds must be accepted, or the test proves little. LLD_CHECK(accepted > 2000);}How this code works: The zero-sum random test
- A repeatable dice.
std::mt19937 random(2026)is a pseudo-random generator with a fixed seed, so every run makes the same 3,000 expenses, and a failure can be replayed exactly.pickis a lambda that captures the generator by reference (&random) and returns a whole number fromlowtohigh, both included. - Random, and often wrong, on purpose. One payer in 21 is “Zed”, a stranger. Each member is in the split with a chance of a half, so some splits are empty. The amount is from −0.02 to 1,000.00, so some are zero or negative.
- Three kinds, in turn.
round % 3picks equal, exact, or percent. For exact parts, each part is a random amount of what is left, and the last part is topped up to make the sum right, except one time in ten, so some exact splits do not add up. Percents do the same out of 100. - What is checked. For each accepted expense, the shares add up to its amount (INV-1). After every expense, accepted or refused, the balances add up to zero (INV-3). Every tenth round also records a random transfer, some of them invalid (to oneself, or of −0.01 or 0.00), and checks INV-3 again.
- The test checks itself. If almost every expense were refused,
the test would pass and prove little.
accepted > 2000makes sure most of the 3,000 were real expenses that moved money.
This is a property: a statement about every input, checked against many generated ones, as in Property-based and table-driven tests. It is how the zero-sum claim becomes more than a comment. A design that dropped a remainder, applied half an expense, or credited the payer a different amount than the shares add up to would fail it in the first few rounds.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
LLD_TEST(ac_7_1_recording_the_suggested_transfers_settles_everyone) { Group group(four); static_cast<void>(shares_of(group, {"Dinner", "Asha", cents(10001), Equal{four}})); static_cast<void>(shares_of(group, {"Hotel", "Ben", units(300), Percent{{{"Chen", 70}, {"Dana", 30}}}})); static_cast<void>(shares_of(group, {"Taxi", "Dana", cents(999), Equal{{"Asha", "Chen"}}})); const std::vector<Transfer> plan = settle_up(group.balances()); LLD_CHECK(plan.size() <= 3); // at most one fewer than the members for (const Transfer& transfer : plan) { LLD_CHECK(transfer.amount > Money{}); LLD_CHECK(!group.record_transfer(transfer).has_value()); } for (const auto& [member, balance] : group.balances()) LLD_CHECK_EQ(balance, Money{});}
LLD_TEST(ac_7_2_the_biggest_debtor_pays_the_biggest_creditor_first) { const Balances balances{{"Asha", units(50)}, {"Ben", units(-80)}, {"Chen", units(30)}, {"Dana", units(0)}}; LLD_CHECK_EQ(settle_up(balances), (std::vector<Transfer>{{"Ben", "Asha", units(50)}, {"Ben", "Chen", units(30)}})); // A tie goes to the name that sorts first, so the plan is repeatable. const Balances tie{{"Asha", units(10)}, {"Ben", units(10)}, {"Chen", units(-10)}, {"Dana", units(-10)}}; LLD_CHECK_EQ(settle_up(tie), (std::vector<Transfer>{{"Chen", "Asha", units(10)}, {"Dana", "Ben", units(10)}}));}
LLD_TEST(ac_7_3_greedy_is_not_always_the_fewest_transfers) { // {Asha +6, Chen -3, Dana -3} and {Ben +5, Eli -5} each add up to zero, // so three transfers can settle them. Greedy first pays Asha from Eli, // the biggest debtor, mixing the two sets, and needs four. const Balances balances{{"Asha", units(6)}, {"Ben", units(5)}, {"Chen", units(-3)}, {"Dana", units(-3)}, {"Eli", units(-5)}}; const std::vector<Transfer> plan = settle_up(balances); LLD_CHECK_EQ(plan.size(), std::size_t{4});
// A three-transfer plan exists, and really does settle everyone. Group group({"Asha", "Ben", "Chen", "Dana", "Eli"}); static_cast<void>(shares_of(group, {"a", "Asha", units(6), Exact{{{"Chen", units(3)}, {"Dana", units(3)}}}})); static_cast<void>(shares_of(group, {"b", "Ben", units(5), Exact{{{"Eli", units(5)}}}})); LLD_CHECK(group.balances() == balances); for (const Transfer& transfer : std::vector<Transfer>{ {"Chen", "Asha", units(3)}, {"Dana", "Asha", units(3)}, {"Eli", "Ben", units(5)}}) { LLD_CHECK(!group.record_transfer(transfer).has_value()); } for (const auto& [member, balance] : group.balances()) LLD_CHECK_EQ(balance, Money{});}
LLD_TEST(ac_7_4_nothing_to_settle_and_bad_balances) { LLD_CHECK(settle_up(Group(four).balances()).empty()); LLD_CHECK_THROWS(settle_up({{"Asha", units(1)}, {"Ben", units(0)}}), std::invalid_argument);}
LLD_TEST(ac_7_5_a_bad_transfer_is_refused_and_changes_nothing) { Group group(four); const Balances before = group.balances(); auto reason = [&group](const Transfer& transfer) { const std::optional<Rejection> rejection = group.record_transfer(transfer); return rejection ? std::optional{rejection->reason} : std::nullopt; }; LLD_CHECK_EQ(reason({"Eve", "Ben", units(5)}), std::optional{Reason::unknown_member}); LLD_CHECK_EQ(reason({"Ben", "Eve", units(5)}), std::optional{Reason::unknown_member}); LLD_CHECK_EQ(reason({"Ben", "Ben", units(5)}), std::optional{Reason::same_member}); LLD_CHECK_EQ(reason({"Ben", "Asha", units(0)}), std::optional{Reason::amount_not_positive}); LLD_CHECK_EQ(reason({"Ben", "Asha", max_amount + cents(1)}), std::optional{Reason::amount_too_large}); LLD_CHECK(group.balances() == before); LLD_CHECK_EQ(reason({"Ben", "Asha", units(5)}), std::optional<Reason>{}); LLD_CHECK_EQ(group.balances().at("Ben"), units(5)); LLD_CHECK_EQ(group.balances().at("Asha"), units(-5));}ac_7_3 is the honest test. It does not check that greedy is good; it
checks that greedy makes four transfers on the balances above, and
then that a three-transfer plan exists and works. If someone later
replaces greedy with an exact search, this test fails, and that is the
point: the test and the documentation must change together.
Checking the tests. The tests were checked by 19 hand-written mutations, applied one at a time by a script to a scratch copy of the step 2 code, which contains all of step 1’s logic (the script is not part of the example). Ten of them are in step 1’s rules: spare cents to the part that lost the least, spare cents in list order with no sort, one spare cent dropped, the exact-parts check off by one, the same check accepting parts that add up to too little, no exact-parts check at all, a negative part of −0.01 allowed, a negative percent of −1 allowed, no check for an empty split, and an unknown payer allowed. The other nine are in the change, and are listed with its tests. Each of the 19 made at least one test fail.
When the requirements change
Section titled “When the requirements change”“Our next trip is to London and New York. We will pay in pounds and dollars, but we want to settle up in euros at the end. We agreed on fixed rates before we left, so use those: one dollar is 0.92 euros, one pound is 1.17.”
One new rule:
- FR-8 Several currencies. A group has a base currency and a table of fixed rates into it, set up once. An expense is in any currency the table knows. Its amount and its split are checked in that currency; the shares, the balances, the transfers, and the plan are in the base currency. The balances still add up to exactly zero.
“Fixed rates, agreed before we left” is what keeps this change small. There is no rate service to stub, no rate that changes between an expense and its split, and no question of which day’s rate to use. Each of those is a real feature of a real app, and each would change the design; this group did not ask for them.
Use cases for the change
Section titled “Use cases for the change”UC-8 Add an expense in another currency.
- AC-8.1 An expense in the base currency is not converted.
- AC-8.2 An expense in another currency is converted at the fixed rate: 10.00 USD is 9.20 EUR, and 300.00 GBP is 351.00 EUR.
- AC-8.3 Conversion rounds to the nearest cent, a half cent up.
- AC-8.4 The total is converted once, then split; converting each share would lose a cent.
- AC-8.5 Exact parts are checked in the expense’s currency, and then share out the converted total in proportion.
- AC-8.6 A currency with no rate is refused with a reason that names it; codes are matched exactly (“usd” and “EUR “ are unknown).
- AC-8.7 An amount that converts to zero cents is refused.
- AC-8.8 An amount that converts to more than the cap is refused, and the cap still applies to the amount in its own currency.
- AC-8.9 A rate table set up wrong is refused: no base code, an empty code, a rate that is not from 1 to the largest rate, or a rate for the base other than one.
What moved
Section titled “What moved”| File | Change |
|---|---|
currency.* |
new: Currency, RateTable, and to_base, the only place an amount changes currency |
split.hpp |
Expense::currency; two new reasons, unknown_currency and rounds_to_zero; Accepted (the base amount and the shares) in SplitResult |
split.cpp |
split_expense takes the rates, converts the total once, uses exact parts as weights, and checks the converted total |
group.* |
owns a RateTable; credits the payer the converted amount; base_currency() |
money.hpp, allocate, settle_up |
unchanged |
| tests | the step 1 tests pass the rates and a currency, "EUR"; nine new tests, ac_8_1 to ac_8_9 |
allocate and settle_up did not change at all, and neither did any
step 1 test’s expected numbers. That is the payoff of having one
rounding rule in one function: a new source of amounts (a conversion)
feeds the same rule, and the rule’s promises still hold.
Text description of the diagram
Group now owns a RateTable as well as its members and balances, and offers base_currency. RateTable holds the base currency’s code and a map from each currency code to its rate in millionths, with two constants, one (a million) and max_rate (a thousand million), and offers base and to_base, which converts an amount from a currency to the base and returns no value for an unknown currency. An Expense gains a currency. An accepted expense is now an Accepted: the amount in the base currency, which the payer is credited, and the shares. Group’s add_expense passes its rates to split_expense, which returns an Accepted or a Rejection.
Diagram source (Mermaid)
classDiagram
class Group {
-vector~MemberId~ members_
-RateTable rates_
-Balances balances_
+base_currency() const Currency&
+add_expense(const Expense&) SplitResult
+record_transfer(const Transfer&) optional~Rejection~
}
class RateTable {
-Currency base_
-map~Currency, int64_t~ rates_
+one$ int64_t
+max_rate$ int64_t
+base() const Currency&
+to_base(Money, const Currency&) optional~Money~
}
class Expense {
+string description
+MemberId paid_by
+Money amount
+Currency currency
+Split split
}
class Accepted {
+Money base_amount
+Shares shares
}
Group *-- RateTable : rates_
Group ..> Expense : adds
Group ..> Accepted : split_expense returnsThe rates
Section titled “The rates”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Fixed exchange rates into the group's base currency, given up front and// never changed. A rate says how many millionths of a base unit one unit// of the other currency is worth: 1 USD = 0.92 EUR is 920'000. Integer// millionths, not a double, so that a conversion is exact arithmetic// followed by one rounding step that the tests can pin down.class RateTable {public: static constexpr std::int64_t one = 1'000'000; // the rate of the base itself // The largest rate: 1,000 base units for one unit. With amounts up to // max_amount, amount * rate is at most 10^18, inside std::int64_t. static constexpr std::int64_t max_rate = 1'000 * one;
// Throws std::invalid_argument for an empty code, a rate that is not // in 1 to max_rate, or a rate for the base other than one: a table set // up wrong is a bug in the caller, not a user's typing mistake. RateTable(Currency base, std::map<Currency, std::int64_t> rates);
[[nodiscard]] const Currency& base() const { return base_; }
// The one place where an amount changes currency. It multiplies by the // rate and rounds to the nearest cent, a half cent up: 0.005 becomes // 0.01 and 0.00499 becomes 0.00. It expects an amount of zero or more // (split_expense refuses negative ones before it gets here); for a // negative amount the integer division would not round half up. // Returns no value for a currency the table does not know. [[nodiscard]] std::optional<Money> to_base(Money amount, const Currency& currency) const;
private: Currency base_; std::map<Currency, std::int64_t> rates_; // includes the base, at one};A rate is a whole number of millionths of a base unit: 0.92 is
920,000. An integer, for the same reason money is one: the conversion
is then exact arithmetic followed by one rounding step, and a test can
say exactly what that step gives. A double rate would make each
conversion depend on the binary value nearest to 0.92, which is not
0.92.
The constructor checks the table once, and throws for a table set up
wrong, because that is a mistake in the code that builds the group,
not something a user typed. try_emplace adds the base at a rate of
one if the caller did not give it, and finds the given rate if they
did, which must then be exactly one.
max_rate is there for the arithmetic again: an amount is at most
109 cents and a rate at most 109 millionths, so
their product is at most 1018, inside std::int64_t.
The one conversion point
Section titled “The one conversion point”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
std::optional<Money> RateTable::to_base(Money amount, const Currency& currency) const { const auto found = rates_.find(currency); if (found == rates_.end()) return std::nullopt; // unknown: the caller says why // amount * rate is the value in millionths of a cent. Adding half of // `one` before the integer division (which rounds down for values // >= 0) rounds to the nearest cent, with a half going up. return cents((amount.cents * found->second + one / 2) / one);}How this code works: to_base, cent by cent
amount.cents * rate is the value in millionths of a cent. Adding
half a million (one / 2) before dividing by a million turns “round
down”, which is what integer division does for values that are zero or
more, into “round to the nearest, a half up”.
| Call | amount.cents × rate |
+ 500,000 | ÷ 1,000,000 | Result |
|---|---|---|---|---|
| 45.67 USD at 920,000 | 4,201,640,000 | 4,202,140,000 | 4,202 | 42.02 EUR (exact value 42.0164) |
| 1.00 USD at 920,000 | 92,000,000 | 92,500,000 | 92 | 0.92 EUR |
| 300.00 GBP at 1,170,000 | 35,100,000,000 | 35,100,500,000 | 35,100 | 351.00 EUR |
| 0.01 at 500,000 (half) | 500,000 | 1,000,000 | 1 | 0.01 (a half cent, up) |
| 0.01 at 499,999 | 499,999 | 999,999 | 0 | 0.00 (just under a half, down) |
ac_8_3 checks these edges and more. The rounding is “half up”
because that is the rule people expect from a receipt. “Half to even”
would be a fair choice too: it avoids a tiny upward lean over many
conversions, and the group did not ask for either. The formula itself
is only right for amounts of zero or more (the header says so:
split_expense refuses a negative amount first). For a negative
amount, adding a half and dividing would not round half up, which is
why the header states the expectation rather than leaving it to be
discovered.
Splitting a converted expense
Section titled “Splitting a converted expense”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Checks an expense against the group's members and rates, and works out// each person's share in the base currency, or says why it cannot. Pure:// it changes nothing.//// The amount and the split are checked in the expense's own currency.// Then the total, and only the total, is converted once (RateTable::to_base// rounds it), checked again in the base currency, and shared out by// allocate. Converting each share apart would round each one, and the// rounded shares need not add up to the rounded total the payer is// credited, which would break the zero-sum invariant.[[nodiscard]] SplitResult split_expense(const Expense& expense, const std::vector<MemberId>& members, const RateTable& rates);VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
SplitResult split_expense(const Expense& expense, const std::vector<MemberId>& members, const RateTable& rates) { // 1. Checks that do not depend on the kind of split. Each returns at // the first problem, so the user hears about one thing at a time. if (expense.amount <= Money{}) { return reject(Reason::amount_not_positive, "The amount must be more than zero."); } if (expense.amount > max_amount) { return reject(Reason::amount_too_large, "The amount is over " + to_string(max_amount) + "."); } // Convert the total now, so that an unknown currency is refused early. // The converted total is checked and used in part 3 below. const std::optional<Money> base_total = rates.to_base(expense.amount, expense.currency); if (!base_total) { return reject(Reason::unknown_currency, "There is no fixed rate from " + expense.currency + " to " + rates.base() + "."); } if (!is_member(members, expense.paid_by)) { return reject(Reason::unknown_member, expense.paid_by + " is not in the group."); } const std::vector<MemberId> names = named_in(expense.split); if (names.empty()) return reject(Reason::empty_split, "Nobody shares this expense."); for (std::size_t i = 0; i < names.size(); ++i) { if (!is_member(members, names[i])) { return reject(Reason::unknown_member, names[i] + " is not in the group."); } // A name seen earlier in the list: the split would be ambiguous. if (std::find(names.begin(), names.begin() + static_cast<std::ptrdiff_t>(i), names[i]) != names.begin() + static_cast<std::ptrdiff_t>(i)) { return reject(Reason::duplicate_member, names[i] + " is listed twice."); } }
// 2. The rule for each kind of split turns it into one weight per name. std::vector<std::int64_t> weights; if (std::holds_alternative<Equal>(expense.split)) { weights.assign(names.size(), 1); // everyone weighs the same } else if (const auto* exact = std::get_if<Exact>(&expense.split)) { for (const auto& [member, part] : exact->parts) { if (part < Money{}) return reject(Reason::negative_part, member + "'s part is negative."); weights.push_back(part.cents); } if (!adds_up_to(weights, expense.amount.cents)) { return reject(Reason::exact_sum_mismatch, "The parts must add up to " + to_string(expense.amount) + " " + expense.currency + "."); } // Step 1 used the parts as they were. Now they may be in another // currency, so they become weights for sharing the base total. // For an expense in the base currency the result is still exactly // the parts: total * part / total divides with nothing left over. } else if (const auto* percent = std::get_if<Percent>(&expense.split)) { for (const auto& [member, share] : percent->parts) { if (share < 0) return reject(Reason::negative_part, member + "'s percent is negative."); weights.push_back(share); } if (!adds_up_to(weights, 100)) { return reject(Reason::percent_sum_mismatch, "The percents must add up to 100."); } }
// 3. The converted total, rounded once by to_base, is what the payer // is credited and what the shares must add up to. if (*base_total == Money{}) { return reject(Reason::rounds_to_zero, "The amount is less than half a cent in " + rates.base() + "."); } if (*base_total > max_amount) { return reject(Reason::amount_too_large, "The amount is over " + to_string(max_amount) + " " + rates.base() + "."); }
// 4. Every kind of split shares out the base total by the one rounding // rule in allocate, so the shares add up to it exactly. const std::vector<Money> parts = allocate(*base_total, weights); Accepted accepted{*base_total, {}}; for (std::size_t i = 0; i < names.size(); ++i) accepted.shares.push_back({names[i], parts[i]}); return accepted;}How this code works: Three expenses from the step 2 demo
The hotel: 300.00 GBP, exact parts 100, 100, 50, 50.
- The amount is positive and under the cap in GBP.
to_basegives 351.00 EUR (the table above). GBP is known, so the expense goes on to the payer and name checks, as in step 1.- The parts are checked in GBP: none negative, and 100 + 100 + 50 + 50 is 300.00, the amount typed. They become weights 10,000, 10,000, 5,000, 5,000.
- 351.00 is not zero and not over the cap.
allocate(35100 cents, weights): Asha’s part is 35,100 × 10,000 ÷ 30,000 = 11,700 with nothing lost, and so on. The shares are 117.00, 117.00, 58.50, 58.50, in proportion to the parts typed, and they add up to 351.00.
The groceries: 45.67 USD at 50/25/25. The total converts once, to
42.02. Then allocate shares 4,202 cents: 2,101 for Asha with nothing
lost, and 1,050 for Ben and Dana, each losing half a cent. One cent is
left; Ben and Dana tie, and Ben, listed first, pays 10.51.
The stamps: 1.00 USD, equal among Ben, Chen, and Dana. The total converts to 92 cents. 92 ÷ 3 is 30, two cents left, all tied: Ben 0.31, Chen 0.31, Dana 0.30. Asha, who paid, is credited 0.92, and the three shares add up to 0.92.
Why are exact parts checked in the expense’s currency? Because that is
what the person typed. They read the hotel bill in pounds and typed
100.00, 100.00, 50.00, 50.00, which add up to the 300.00 on the bill.
Checked in euros, the parts would first have to be converted one by
one, each rounded, and they need not add up to the converted total, so
a correct split could be refused. ac_8_5 also checks the other way:
parts of 200.00 and 151.00, which add up to the euro value, are
refused, because the bill was 300.00 pounds.
The parts then become weights for the converted total. For an expense
in the base currency nothing changes: the total and the weights are the
same numbers, and each division comes out exact, so the shares are the
parts as typed (ac_3_1 still passes). For another currency the shares
keep the parts’ proportions, and the one rounding rule handles any
cent left over.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
SplitResult Group::add_expense(const Expense& expense) { SplitResult result = split_expense(expense, members_, rates_); // Refused: return the rejection before anything is changed. if (std::holds_alternative<Rejection>(result)) return result;
// The shares add up to the base amount (split_expense promises it), so // the credit and the debits cancel out and the balances still sum to // exactly zero. The base amount was rounded once from the expense's // currency; that rounding (at most half a cent) is between the group // and the outside world, and no member gains or loses it against // another, because the payer is credited the same rounded number that // the shares add up to. const Accepted& accepted = std::get<Accepted>(result); balances_[expense.paid_by] += accepted.base_amount; for (const Share& share : accepted.shares) balances_[share.member] -= share.amount; return result;}The payer is credited base_amount, the same rounded number the
shares add up to. That is what keeps INV-3 exact. The conversion did
round, by at most half a cent, but that half cent is between the group
and the outside world (Asha’s card was charged 1.00 USD; the group
records 0.92 EUR). Inside the group, nobody gains or loses it against
anybody else.
Convert once, not per share
Section titled “Convert once, not per share”The new refusals
Section titled “The new refusals”- Unknown currency. A code the table does not have, matched exactly: “CHF”, “”, “usd”, and “EUR “ (with a space) are all unknown. The check runs early, right after the amount checks, so the person hears about the currency before anything about the split.
- Converts to zero. An amount worth less than half a cent in the
base currency (in
ac_8_7, a made-up currency at one millionth of a euro) would give a total of zero, andallocatewould share out nothing. An expense that moves no money is almost surely a mistake, so it is refused. - Over the cap after conversion. The cap is checked twice: on the
amount in its own currency (as in step 1) and on the converted total.
A currency worth more than the base can turn an amount under the cap
into a total over it, and the total is what
allocatemultiplies.
Step 2 tests
Section titled “Step 2 tests”The step 1 tests run against step 2 with the rates and a currency,
"EUR", and the same expected numbers. Then:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
LLD_TEST(ac_8_1_a_base_currency_expense_is_not_converted) { Group group(four, euros()); const Accepted dinner = accepted_of(group, {"Dinner", "Asha", cents(10001), "EUR", Equal{four}}); LLD_CHECK_EQ(dinner.base_amount, cents(10001)); LLD_CHECK_EQ(dinner.shares, (Shares{{"Asha", cents(2501)}, {"Ben", cents(2500)}, {"Chen", cents(2500)}, {"Dana", cents(2500)}}));}
LLD_TEST(ac_8_2_a_foreign_expense_is_converted_at_the_fixed_rate) { Group group(four, euros()); LLD_CHECK_EQ(accepted_of(group, {"Taxi", "Ben", units(10), "USD", Equal{{"Ben", "Chen"}}}).base_amount, cents(920)); LLD_CHECK_EQ(group.balances().at("Ben"), cents(460)); // paid 9.20 EUR, owes 4.60 of it LLD_CHECK_EQ(group.balances().at("Chen"), cents(-460)); LLD_CHECK_EQ(accepted_of(group, {"Hotel", "Chen", units(300), "GBP", Equal{four}}).base_amount, units(351)); LLD_CHECK_EQ(group.base_currency(), Currency("EUR"));}
LLD_TEST(ac_8_3_conversion_rounds_to_the_nearest_cent_a_half_up) { const RateTable rates("EUR", {{"HLF", 500'000}, {"LOW", 499'999}, {"USD", 920'000}, {"A", 1'004'999}, {"B", 1'005'000}}); LLD_CHECK_EQ(rates.to_base(cents(1), "HLF"), std::optional{cents(1)}); // 0.5 cent: up LLD_CHECK_EQ(rates.to_base(cents(3), "HLF"), std::optional{cents(2)}); // 1.5: up LLD_CHECK_EQ(rates.to_base(cents(1), "LOW"), std::optional{cents(0)}); // 0.499999: down LLD_CHECK_EQ(rates.to_base(units(1), "A"), std::optional{units(1)}); // 100.4999: down LLD_CHECK_EQ(rates.to_base(units(1), "B"), std::optional{cents(101)}); // 100.5: up LLD_CHECK_EQ(rates.to_base(cents(4567), "USD"), std::optional{cents(4202)}); // 4201.64: up LLD_CHECK_EQ(rates.to_base(cents(4567), "EUR"), std::optional{cents(4567)}); // the base: as is LLD_CHECK_EQ(rates.to_base(cents(0), "USD"), std::optional{cents(0)});}
LLD_TEST(ac_8_4_the_total_is_converted_once_then_split) { Group group(four, euros()); const Accepted stamps = accepted_of(group, {"Stamps", "Asha", units(1), "USD", Equal{{"Ben", "Chen", "Dana"}}}); LLD_CHECK_EQ(stamps.base_amount, cents(92)); LLD_CHECK_EQ(stamps.shares, (Shares{{"Ben", cents(31)}, {"Chen", cents(31)}, {"Dana", cents(30)}})); LLD_CHECK_EQ(group.balances().at("Asha"), cents(92)); LLD_CHECK_EQ(sum_of(group.balances()), Money{});
// Why not convert each share? Split in USD first (34, 33, 33 cents) // and convert each one, and the shares come to 91 cents, not 92: the // payer would be owed a cent that nobody owes. Money converted_apart; for (const Money share : allocate(units(1), {1, 1, 1})) converted_apart += *euros().to_base(share, "USD"); LLD_CHECK_EQ(converted_apart, cents(91));}
LLD_TEST(ac_8_5_exact_parts_are_checked_in_the_expense_currency) { Group group(four, euros()); // 300.00 GBP is 351.00 EUR; the parts are in GBP and split it by weight. LLD_CHECK_EQ(shares_of(group, {"Hotel", "Chen", units(300), "GBP", Exact{{{"Asha", units(100)}, {"Ben", units(100)}, {"Chen", units(50)}, {"Dana", units(50)}}}}), (Shares{{"Asha", units(117)}, {"Ben", units(117)}, {"Chen", cents(5850)}, {"Dana", cents(5850)}})); // Parts that add up to the EUR value, not the GBP amount, are refused. LLD_CHECK_EQ(refusal_of(group, {"Hotel", "Chen", units(300), "GBP", Exact{{{"Asha", units(200)}, {"Ben", units(151)}}}}), std::optional{Reason::exact_sum_mismatch}); // 0.10 USD is 9.2 cents, rounded to 9. The parts (5 and 5 cents) make // 4.5 each: both lose half a cent, so the first listed gets the spare. LLD_CHECK_EQ(shares_of(group, {"Gum", "Ben", cents(10), "USD", Exact{{{"Chen", cents(5)}, {"Ben", cents(5)}}}}), (Shares{{"Chen", cents(5)}, {"Ben", cents(4)}})); // Uneven parts keep their proportion: 1.00 USD as 0.25 + 0.75 is 0.92 // EUR as 0.23 + 0.69. LLD_CHECK_EQ(shares_of(group, {"Pens", "Ben", units(1), "USD", Exact{{{"Chen", cents(25)}, {"Dana", cents(75)}}}}), (Shares{{"Chen", cents(23)}, {"Dana", cents(69)}})); LLD_CHECK_EQ(sum_of(group.balances()), Money{});}
LLD_TEST(ac_8_6_an_unknown_currency_is_refused_with_a_reason) { Group group(four, euros()); for (const Currency& code : {Currency("CHF"), Currency(""), Currency("usd"), Currency("EUR ")}) { LLD_CHECK_EQ(refusal_of(group, {"Fondue", "Ben", units(80), code, Equal{four}}), std::optional{Reason::unknown_currency}); } const SplitResult result = group.add_expense({"Fondue", "Ben", units(80), "CHF", Equal{four}}); const auto* rejection = std::get_if<Rejection>(&result); LLD_CHECK(rejection != nullptr && rejection->detail.find("CHF") != std::string::npos); LLD_CHECK_EQ(euros().to_base(units(1), "CHF"), std::optional<Money>{});}
LLD_TEST(ac_8_7_an_amount_that_converts_to_zero_is_refused) { // One millionth of a euro per unit: 1 cent is worth 0.000001 cent. Group group(four, RateTable("EUR", {{"TNY", 1}})); LLD_CHECK_EQ(refusal_of(group, {"Crumb", "Ben", cents(1), "TNY", Equal{four}}), std::optional{Reason::rounds_to_zero}); // 5,000 cents of it is worth 0.005 cent, still zero. 500,000 cents is // worth half a cent, which rounds up to one. LLD_CHECK_EQ(refusal_of(group, {"Crumb", "Ben", cents(5'000), "TNY", Equal{four}}), std::optional{Reason::rounds_to_zero}); LLD_CHECK_EQ(accepted_of(group, {"Crumb", "Ben", cents(500'000), "TNY", Equal{four}}).base_amount, cents(1));}
LLD_TEST(ac_8_8_an_amount_that_converts_to_over_the_cap_is_refused) { Group group(four, RateTable("EUR", {{"DBL", 2'000'000}})); LLD_CHECK_EQ(refusal_of(group, {"Villa", "Ben", cents(max_amount.cents / 2 + 1), "DBL", Equal{four}}), std::optional{Reason::amount_too_large}); LLD_CHECK_EQ(accepted_of(group, {"Villa", "Ben", cents(max_amount.cents / 2), "DBL", Equal{four}}).base_amount, max_amount); // The cap on the amount itself is still checked in its own currency. LLD_CHECK_EQ(refusal_of(group, {"Villa", "Ben", max_amount + cents(1), "EUR", Equal{four}}), std::optional{Reason::amount_too_large});}
LLD_TEST(ac_8_9_a_rate_table_set_up_wrong_is_refused) { LLD_CHECK_THROWS(RateTable("", {}), std::invalid_argument); LLD_CHECK_THROWS(RateTable("EUR", {{"", 1'000'000}}), std::invalid_argument); LLD_CHECK_THROWS(RateTable("EUR", {{"USD", 0}}), std::invalid_argument); LLD_CHECK_THROWS(RateTable("EUR", {{"USD", -920'000}}), std::invalid_argument); LLD_CHECK_THROWS(RateTable("EUR", {{"USD", RateTable::max_rate + 1}}), std::invalid_argument); LLD_CHECK_THROWS(RateTable("EUR", {{"EUR", 999'999}}), std::invalid_argument); LLD_CHECK_THROWS(RateTable("EUR", {{"EUR", 1'000'001}}), std::invalid_argument); // The edges that are allowed: the base at exactly one, and max_rate. const RateTable edges("EUR", {{"EUR", RateTable::one}, {"MAX", RateTable::max_rate}}); LLD_CHECK_EQ(edges.to_base(cents(1), "EUR"), std::optional{cents(1)}); LLD_CHECK_EQ(edges.to_base(max_amount, "MAX"), std::optional{cents(max_amount.cents * 1'000)}); LLD_CHECK_EQ(RateTable("EUR", {}).to_base(cents(7), "EUR"), std::optional{cents(7)});}The random test now picks one of four currencies for each expense: EUR, USD, GBP, and CHF, which has no rate.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The key invariant, against many random expenses, some of them invalid:// every split's shares add up to its amount converted once to EUR, and// the balances add up to exactly zero after every expense and transfer,// accepted or refused. The seed is fixed, so a failure happens again on// the next run.LLD_TEST(ac_6_1_balances_always_add_up_to_zero) { const std::vector<MemberId> people = {"Asha", "Ben", "Chen", "Dana", "Eli", "Fay", "Gus"}; Group group(people, euros()); std::mt19937 random(2026); auto pick = [&random](std::int64_t low, std::int64_t high) { return std::uniform_int_distribution<std::int64_t>(low, high)(random); }; int accepted = 0; for (int round = 0; round < 3000; ++round) { // Pick a payer (sometimes a stranger) and some of the members. const MemberId payer = pick(0, 20) == 0 ? "Zed" : people[static_cast<std::size_t>(pick(0, 6))]; std::vector<MemberId> among; for (const MemberId& person : people) { if (pick(0, 1) == 1) among.push_back(person); } const Money amount = cents(pick(-2, 100'000)); // Three currencies with a rate, and CHF, which has none. const std::array<Currency, 4> codes = {"EUR", "USD", "GBP", "CHF"}; const Currency currency = codes[static_cast<std::size_t>(pick(0, 3))]; Split split = Equal{among}; if (round % 3 == 1) { // exact parts: random, then the last fixed up (mostly) Exact exact; Money left = amount; for (const MemberId& person : among) { const Money part = cents(pick(0, left.cents > 0 ? left.cents : 0)); exact.parts.emplace_back(person, part); left -= part; } if (!exact.parts.empty() && pick(0, 9) != 0) exact.parts.back().second += left; split = exact; } else if (round % 3 == 2) { // percents: the same idea out of 100 Percent percent; int left = 100; for (const MemberId& person : among) { const int share = static_cast<int>(pick(0, left)); percent.parts.emplace_back(person, share); left -= share; } if (!percent.parts.empty() && pick(0, 9) != 0) percent.parts.back().second += left; split = percent; } const SplitResult result = group.add_expense({"random", payer, amount, currency, split}); if (const auto* expense = std::get_if<Accepted>(&result)) { ++accepted; // The base amount is the total converted once, and the shares // add up to exactly it. LLD_CHECK_EQ(std::optional{expense->base_amount}, euros().to_base(amount, currency)); Money sum; for (const Share& share : expense->shares) sum += share.amount; LLD_CHECK_EQ(sum, expense->base_amount); } LLD_CHECK_EQ(sum_of(group.balances()), Money{});
if (round % 10 == 0) { // now and then, someone pays someone back static_cast<void>(group.record_transfer({people[static_cast<std::size_t>(pick(0, 6))], people[static_cast<std::size_t>(pick(0, 6))], cents(pick(-1, 5'000))})); LLD_CHECK_EQ(sum_of(group.balances()), Money{}); } } // Most rounds must be accepted, or the test proves little. LLD_CHECK(accepted > 1500); // a quarter use CHF, which has no rate}It checks one more thing for every accepted expense: that its
base_amount is exactly what to_base gives for the total, so the
total really was converted once. The shares must add up to that, and
after every step the balances must add up to zero, to the cent. A
quarter of the expenses use CHF and are refused, so the floor on
accepted expenses is 1,500 instead of 2,000.
The nine mutations in the change were: rounding down instead of to the nearest, a half rounding down, no check for a total that converts to zero, the cap after conversion off by one, splitting the unconverted amount, crediting the payer the unconverted amount, allowing a rate of zero, not checking the base’s rate, and allowing a base rate above one. Each made at least one step 2 test fail.
The step 2 demo
Section titled “The step 2 demo”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// 1 USD = 0.92 EUR and 1 GBP = 1.17 EUR, fixed for the whole trip.Group trip({"Asha", "Ben", "Chen", "Dana"}, RateTable("EUR", {{"USD", 920'000}, {"GBP", 1'170'000}}));
add(trip, {"Dinner", "Asha", units(100), "EUR", Equal{{"Asha", "Ben", "Chen", "Dana"}}});// 10.00 USD is 9.20 EUR; 920 / 3 leaves 2 cents, for Asha and Ben.add(trip, {"Taxi", "Ben", units(10), "USD", Equal{{"Asha", "Ben", "Chen"}}});// The parts are checked in GBP (they add up to 300.00), then used as// weights for the 351.00 EUR the hotel came to.add(trip, {"Hotel", "Chen", units(300), "GBP", Exact{{{"Asha", units(100)}, {"Ben", units(100)}, {"Chen", units(50)}, {"Dana", units(50)}}}});// 45.67 USD is 42.0164 EUR, rounded once to 42.02, then split.add(trip, {"Groceries", "Dana", cents(4567), "USD", Percent{{{"Asha", 50}, {"Ben", 25}, {"Dana", 25}}}});// 1.00 USD is 0.92 EUR, split three ways. Converting each USD share// (0.34, 0.33, 0.33) on its own would give 0.31 + 0.30 + 0.30 = 0.91.add(trip, {"Stamps", "Asha", units(1), "USD", Equal{{"Ben", "Chen", "Dana"}}});
add(trip, {"Fondue", "Ben", units(80), "CHF", Equal{{"Asha", "Ben"}}});show(trip);
std::cout << "Settle up in " << trip.base_currency() << ":\n";for (const Transfer& transfer : settle_up(trip.balances())) { std::cout << " " << transfer.from << " pays " << transfer.to << " " << to_string(transfer.amount) << "\n"; static_cast<void>(trip.record_transfer(transfer)); // accepted: it came from the plan}show(trip);Dinner (100.00 EUR, paid by Asha): 100.00 EUR = Asha 25.00, Ben 25.00, Chen 25.00, Dana 25.00Taxi (10.00 USD, paid by Ben): 9.20 EUR = Asha 3.07, Ben 3.07, Chen 3.06Hotel (300.00 GBP, paid by Chen): 351.00 EUR = Asha 117.00, Ben 117.00, Chen 58.50, Dana 58.50Groceries (45.67 USD, paid by Dana): 42.02 EUR = Asha 21.01, Ben 10.51, Dana 10.50Stamps (1.00 USD, paid by Asha): 0.92 EUR = Ben 0.31, Chen 0.31, Dana 0.30Fondue (80.00 CHF, paid by Ben): refused, unknown currency. There is no fixed rate from CHF to EUR.Balances in EUR: Asha -65.16 Ben -146.69 Chen 264.13 Dana -52.28 (sum 0.00)Settle up in EUR: Ben pays Chen 146.69 Asha pays Chen 65.16 Dana pays Chen 52.28Balances in EUR: Asha 0.00 Ben 0.00 Chen 0.00 Dana 0.00 (sum 0.00)- Dinner is in euros, the base, and splits as in step 1.
- Taxi, 10.00 USD, is 9.20 EUR. 920 cents among three leaves two cents, so Asha and Ben pay 3.07 and Chen 3.06.
- Hotel, 300.00 GBP, is 351.00 EUR, shared by the parts typed in pounds: 117.00, 117.00, 58.50, 58.50.
- Groceries, 45.67 USD, is 42.02 EUR after one rounding, then split.
- Stamps, 1.00 USD, is 0.92 EUR, split three ways. The comment in the demo shows what converting each share would have given.
- Fondue in CHF is refused: there is no fixed rate for it.
- The balances are in euros and add up to 0.00, and the plan is three transfers to Chen, as before, with euro amounts.
Honest limits of the change
Section titled “Honest limits of the change”- Every currency has 100 minor units.
Moneycounts cents, and the rates turn cents into cents. That is right for the euro, the dollar, and the pound, and wrong for the Japanese yen, which has no minor unit, and for currencies such as the Kuwaiti dinar, which have a thousand. Supporting them means storing each currency’s number of minor units next to its rate, and scaling into_base; the rest of the design would not change, because onlyto_basemoves an amount between currencies. - Rates have a floor and a ceiling. The smallest rate is one millionth, and a rate is held to six decimal places, so a rate such as 0.9234567 cannot be stored exactly. The largest is 1,000 base units per unit, which keeps the arithmetic inside 64 bits. A pair of currencies further apart than that cannot be in one table.
- Fixed rates only. One table for the group’s whole life, with no dates. An expense is converted at the table’s rate, whatever the rate was on the day it was paid, and an expense cannot be paid back in the currency it was paid in. A real app would store the rate used with each expense, so that a later rate change could not silently change old balances.
- One base currency for everything after the split. Balances, transfers, and the plan are in euros. A member who wants to pay back in dollars converts outside the app.
Presenting it in an interview
Section titled “Presenting it in an interview”A plan for 45 minutes, using the time boxes from The design workflow:
| Time | What to do | What to say |
|---|---|---|
| About 5 min | Ask how money is typed, which splits there are, what happens to a left-over cent, whether a payer must share, and what “settle” means. | “Seven people share a 0.13 bill. Who pays the spare cents, and will they get the same answer tomorrow?” |
| 5 min | Sketch Money, the split variant, Expense, split_expense, Group with its balances, and settle_up. Say what is pure. |
“Splitting is a pure function. The group only checks it and applies it, so a refusal changes nothing.” |
| 10–15 min | Write allocate, then split_expense with its checks in order. State INV-1 and INV-3. |
“Every split ends in one rounding rule, and the shares always add up to the amount.” |
| 10 min | Walk the groceries split cent by cent, then the greedy plan, and show the case where it makes four transfers where three would do. | “Greedy is at most n − 1 transfers and easy to explain. The fewest is a much harder problem.” |
| About 5 min | Take a change: currencies at fixed rates. | “Convert the total once, then split it, and credit the payer that same number. The sum stays at zero.” |
What is usually expected at each level
| Level | Usually expected |
|---|---|
| Junior | Members, expenses, an equal split, balances, and a list of who owes whom; money in integer cents; a few tests with hand-worked numbers. |
| Mid-level | All of the above, plus: exact and percent splits with checks and reasons; one rule for left-over cents that is fair and repeatable; balances that add up to zero, checked by a test; a settle-up plan; a refusal that changes nothing. |
| Senior | All of the above, plus: a closed set of splits as a variant, with the reason; overflow bounds stated and tested; a random test of the invariant; the greedy plan’s limits stated honestly; currencies converted once at one point, with the limits of fixed rates. |
These are this site’s judgement of common practice, as on How to approach a case study, not any company’s rubric.
Questions an interviewer may ask
Section titled “Questions an interviewer may ask”- “Why integer cents and not a
double?” Adoublecannot hold 0.10 exactly, so sums drift and two equal-looking amounts can compare unequal. With cents,+,-, and==are exact, and rounding happens only where the design says it does, inallocateandto_base. - “Who pays the extra cent, and why them?” Whoever rounding cost the most, with ties to the member listed first. Nobody’s share is ever more than a cent from their fair part, the shares always add up to the amount, and the same expense always splits the same way.
- “Why a variant and not a
SplitRuleinterface?” The set of splits is closed and small, each one needs different checks, and withstd::visitthe compiler can check that every place handles every kind. An interface earns its place when splits come from outside the code, such as plug-ins, or when the set keeps growing. - “How do you know the balances add up to zero?” Every accepted expense credits the payer the same number the shares add up to, and every transfer moves one amount from one member to another. A seeded random test adds thousands of expenses and transfers and checks the sum after every one.
- “Is your settle-up the fewest transfers?” No. It is at most n − 1 transfers, and the tests show a case where it makes four and three would do. The fewest is a much harder problem, and for a small group the difference is rarely worth the code.
- “Two people add expenses at the same time. What happens?” In this design, it is not handled: the group is single-threaded. A server would put the group behind one lock, or one queue, so that each expense is checked and applied as a unit; see the next section.
- “An expense was typed wrong. How do you fix it?” Here, it cannot be undone: the group keeps only balances, so the best a person can do is record a transfer that offsets it. A real app would keep the list of expenses and work out balances from it, so that an edit or delete is a change to the list, with history.
- “Why not convert each share?” Each conversion rounds, and the rounded shares need not add up to the converted total, so the balances would drift from zero a cent at a time.
Production limitations
Section titled “Production limitations”- No expense history. The group keeps only balances. It cannot list, edit, or delete an expense, show who added it, or rebuild the balances from the list. A real app would store expenses and transfers as records and derive balances from them, which also makes a mistaken expense something to undo rather than something to correct by hand.
- Single-threaded and in memory. Concurrency is not handled: two
threads adding expenses to one
Groupat once would race on the balances. Nothing is saved, so a restart loses everything. A service would keep each group behind one lock or one queue and in a database, with each expense written in one transaction with its balance changes. - Names are the ids. Two members called “Sam” cannot both join, and a rename would have to touch every record. Real members would have ids, with names for display.
- Greedy is not minimal. At most n − 1 transfers, but not always the fewest, as the 4-versus-3 case shows.
- Whole percents only. 33.5 % cannot be typed. Allowing it means a finer unit for percents (tenths or hundredths) and a new total to check against.
- Currencies. Fixed rates, 100 minor units each, and one base currency; see the limits of the change above.
- A cap on every amount. 10 million in any currency, so that every
product fits in 64 bits. Larger amounts would need a wider type for
the products in
allocateandto_base. - No accounts or permissions. Anyone with the group can add any expense in anyone’s name.
Traceability
Section titled “Traceability”| Requirement | Design element | Code | Tests | Status |
|---|---|---|---|---|
| FR-1 group | Group constructor, members(), balances() |
step 1 group.* |
ac_1_1_…, ac_1_2_… |
Tested |
| FR-2 expense | Expense, split_expense, add_expense |
step 1 split.*, group.cpp |
ac_2_1_…, ac_5_4_… |
Tested |
| FR-3 splits | Split = variant<Equal, Exact, Percent> |
step 1 split.* |
ac_2_1_…, ac_3_1_…, ac_4_1_… |
Tested |
| FR-4 rounding | allocate, the one remainder rule |
step 1 split.cpp |
ac_2_2_… to ac_2_4_…, ac_4_3_… to ac_4_5_…, ac_6_2_… |
Tested |
| FR-5 refusals | Reason, Rejection, checks in order |
step 1 split.*, group.cpp |
ac_1_2_…, ac_3_2_…, ac_3_3_…, ac_4_2_…, ac_5_1_… to ac_5_3_…, ac_7_5_… |
Tested |
| FR-6 balances | Group::balances_, credit the payer, debit the shares |
step 1 group.cpp |
ac_6_1_… (random) |
Tested |
| FR-7 settle up | settle_up, greedy |
step 1 group.cpp |
ac_7_1_… to ac_7_4_… |
Tested |
| FR-8 currencies | RateTable, to_base, Accepted::base_amount |
step 2 currency.*, split.cpp, group.cpp |
ac_8_1_… to ac_8_9_…, random test |
Tested |
| NFR-1 exact money | Money as std::int64_t cents; integer rates |
money.hpp, step 2 currency.* |
every test compares cents | Tested |
| NFR-2 repeatable | ties to the member listed first; std::stable_sort |
step 1 split.cpp |
ac_2_3_…, ac_4_4_… |
Tested |
| NFR-3 no overflow | max_amount, max_rate, the checks before multiplying |
money.hpp, split.cpp, currency.* |
ac_5_1_…, ac_8_8_…, ac_8_9_… |
Tested |
| NFR-4 testable | split_expense is a pure function |
step 1 split.hpp |
ac_6_2_… calls allocate on its own |
By design |
| NFR-5 single-threaded | no locks; one owner | group.hpp |
none | Limitation |
Exercise
Section titled “Exercise”Exercise: Split by shares
The group’s next trip is a ski chalet. Some of them stay three nights and some two, and they want to split the chalet by shares: each member is given a whole number of shares (nights stayed), and the amount is split in proportion.
Add a fourth split, ByShares, to step 1:
- Write the type and add it to
Split. - Decide which checks it needs and which reasons they give. Can a share be zero? Can they all be zero?
- Find every place that must change. Which of them will the compiler point out for you, and which will it not?
- Work out by hand what 100.00 by 3 and 2 shares gives, and what 10.00 by 2 and 1 shares gives, and write those as tests.
Show the explained answer
IllustrativeA fragment for explanation; not compiled on its own.
// split.hpp: the new kind of split.struct ByShares { std::vector<std::pair<MemberId, int>> parts; // whole shares, such as nights stayed};using Split = std::variant<Equal, Exact, Percent, ByShares>;// Reason gains no_shares, and to_string gains:// case Reason::no_shares: return "no shares";
// split.cpp, in named_in: the members a ByShares split names.} else if (const auto* by = std::get_if<ByShares>(&split)) { for (const auto& [member, count] : by->parts) names.push_back(member);}
// split.cpp, in split_expense: shares become the weights for allocate.} else if (const auto* by = std::get_if<ByShares>(&expense.split)) { std::int64_t total_shares = 0; for (const auto& [member, count] : by->parts) { if (count < 0) return reject(Reason::negative_part, member + "'s share is negative."); weights.push_back(count); // one weight per member, in the order listed total_shares += count; } // A zero share is fine (someone who stayed no nights but is listed); // all zero would leave nobody to pay. if (total_shares == 0) return reject(Reason::no_shares, "Somebody must have a share.");}The checks. A negative share is refused, reusing
negative_part. A zero share is allowed, as a zero percent is, and
that member is never given a cent (allocate gives no spare cent to a
zero weight). All zero is refused with a new reason, no_shares,
because allocate needs a positive total weight. The name checks
(nobody missing from the group, nobody twice, somebody named) already
run on what named_in returns, so they cover ByShares for free once
named_in knows it. allocate and the rounding rule do not change at
all.
What the compiler finds. With the project’s warnings as errors,
forgetting the new case in to_string stops the build: the switch
over Reason no longer handles every value (-Wswitch). Forgetting
named_in is silent: the get_if chain simply has no branch for
it, so every ByShares split looks as if it names nobody and is
refused as empty_split. The tests catch that one, not the compiler.
Forgetting the branch in split_expense leaves the weights
empty, and allocate throws std::invalid_argument (from reading the
code; we did not run that one). This is the cost of the get_if
chain: a std::visit with an overload for each kind would have made
the compiler point at both of the silent places too.
The numbers. 100.00 by 3 and 2 shares: 10,000 × 3 ÷ 5 = 6,000 and 10,000 × 2 ÷ 5 = 4,000, so 60.00 and 40.00, nothing left over. 10.00 by 2 and 1: 1,000 × 2 ÷ 3 = 666 with two thirds of a cent lost, and 1,000 × 1 ÷ 3 = 333 with a third lost. One cent is left, and the first member lost more, so the shares are 6.67 and 3.33.
This answer was built and checked in a scratch copy of step 1 (not
part of the example), with tests for those two splits and for all-zero
shares (no_shares), a negative share (negative_part), an empty list
(empty_split), and a name given twice (duplicate_member), each
refusal leaving the balances unchanged. All 27 tests passed under GCC,
Clang, and the AddressSanitizer and UndefinedBehaviorSanitizer build.
Summary
Section titled “Summary”- Keep money in integer cents, and round in as few places as
possible: here, one rule for splitting (
allocate) and one for converting (to_base). - Every split ends in the same remainder rule: the cent goes to whoever rounding cost most, ties to the member listed first. The shares add up to the amount, nobody is more than a cent from fair, and the result is the same every time.
- A small, closed set of rules with different checks fits a
std::variantbetter than a Strategy hierarchy. An interface earns its place when the rules come from outside the code. - Make splitting a pure function, and let the group check and then apply, so a refusal changes nothing.
- Balances add up to zero because each change credits and debits the same number. A seeded random test checks it after every step.
- Be honest about greedy settle-up: at most n − 1 transfers, not always the fewest.
- For currencies, convert the total once, split the converted total, and credit the payer that same number. Check what the person typed in the currency they typed it in.