Add splitwise module: equal/exact/percent/share split strategies with largest-remainder paise arithmetic, derived ledger, greedy and exact debt simplification, concurrency control (13 tests, 12 transcripts)

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b4aCTv6BYCer55YdjZ
This commit is contained in:
Claude
2026-11-17 23:16:53 +05:30
parent c57031aaeb
commit eef175d669
42 changed files with 1772 additions and 0 deletions
+1
View File
@@ -25,6 +25,7 @@ One module per article. This repository currently holds:
| [`matrix`](matrix/) | Matrix Programs in Java: Addition, Multiplication, Transpose, Spiral and Rotation | this commit | | [`matrix`](matrix/) | Matrix Programs in Java: Addition, Multiplication, Transpose, Spiral and Rotation | this commit |
| [`rate-limiter`](rate-limiter/) | Low-Level Design: Rate Limiter in Java (Token Bucket, Sliding Window) + Spring Boot | this commit | | [`rate-limiter`](rate-limiter/) | Low-Level Design: Rate Limiter in Java (Token Bucket, Sliding Window) + Spring Boot | this commit |
| [`bookmyshow`](bookmyshow/) | Low-Level Design: BookMyShow Seat Booking in Java (Handling Concurrent Bookings) | this commit | | [`bookmyshow`](bookmyshow/) | Low-Level Design: BookMyShow Seat Booking in Java (Handling Concurrent Bookings) | this commit |
| [`splitwise`](splitwise/) | Low-Level Design: Splitwise (Expense Sharing) in Java | this commit |
## `collections` module ## `collections` module
+57
View File
@@ -0,0 +1,57 @@
# splitwise
Companion code for the ankurm.com article **Low-Level Design: Splitwise (Expense Sharing) in Java**.
An expense-sharing core: four ways to split a bill (equal, exact, percent, shares) with exact paise arithmetic, a ledger derived from
the expense log, and two debt simplifiers (greedy, and an exact search that finds the true minimum number of payments). Every figure and
console line in the article is quoted from a file in `output/`, which the JUnit tests write while asserting the same numbers. There is no
`docs/` folder: the explanations live in the article itself.
## Versions
| Component | Version | Verified against |
|---|---|---|
| JDK | Temurin 25.0.5+8 (LTS) | `java -version` |
| JUnit | 6.1.3 | `junit-bom` `maven-metadata.xml` on Maven Central (latest GA) |
| Maven | 3.9.11 | `mvn -version` |
No frameworks and no runtime dependencies: everything in `src/main` is plain Java.
## Quickstart
```bash
cd splitwise
export JAVA_HOME=/path/to/jdk-25 PATH="$JAVA_HOME/bin:$PATH"
./scripts/run-all.sh # runs every test and regenerates output/*.txt
```
The first Maven run must be online so the plugins land in the local cache. Two transcripts contain figures that depend on timing
(`04c-simplify-cost.txt`, `06b-concurrency-control.txt`); they say so in their first line and differ from run to run by design.
## The pieces
| Class | Role |
|---|---|
| `Money` | text to and from whole paise; the rest of the code never sees a `double` |
| `Apportion` | largest remainder division: shares always add up to the total exactly |
| `SplitStrategy` | the one interface a split implements: `participants()` and `split(total)` |
| `EqualSplit`, `ExactSplit`, `PercentSplit`, `ShareSplit` | the four strategies; each validates its own input |
| `Expense`, `Transfer`, `User` | immutable records: an expense and what each person owes, a payment, a person |
| `Ledger` | net balance per person plus a per-pair view, built by applying expenses and transfers in order |
| `Group` | members, the expense log, and synchronized `addExpense` / `settle` |
| `DebtSimplifier` | net balances in, short list of payments out |
| `GreedyDebtSimplifier` | biggest debtor pays biggest creditor; at most n - 1 payments |
| `OptimalDebtSimplifier` | subset DP over zero-sum groups; the true minimum, up to 20 people |
| `SplitwiseService` | registers users, creates groups |
## Transcripts
| File | Written by | What it shows |
|---|---|---|
| `01-happy-path.txt` | `HappyPathTest` | a four-friend trip: shares, net balances, pairwise vs simplified debts |
| `02-rounding.txt`, `02b-rounding-property.txt` | `RoundingTest` | why `double` and plain division fail; 200,000 seeded divisions |
| `03-validation.txt` | `ValidationTest` | eleven bad requests, the exact message for each, ledger untouched |
| `04-simplify.txt`, `04b-simplify-random.txt`, `04c-simplify-cost.txt` | `SimplifyTest` | where greedy is not minimal; 1,500 seeded cases cross-checked by backtracking; cost of the exact search |
| `05-settle-up.txt`, `05b-replay.txt` | `SettleUpTest` | recording payments; the ledger rebuilt from the log |
| `06-concurrency.txt`, `06b-concurrency-control.txt` | `ConcurrencyTest` | eight threads on one group; the same idea with an unsynchronized map |
| `07-pitfalls.txt` | `PitfallsTest` | six traps, each reproduced |
+28
View File
@@ -0,0 +1,28 @@
Four friends, five expenses, four split strategies
==================================================
Expenses (shares in paise-exact rupees)
#1 Hotel (equal) paid by asha Rs 12000.00 asha=Rs 3000.00 bala=Rs 3000.00 chitra=Rs 3000.00 dev=Rs 3000.00
#2 Dinner (equal, 3 people) paid by bala Rs 100.00 asha=Rs 33.34 bala=Rs 33.33 chitra=Rs 33.33
#3 Cab (exact) paid by chitra Rs 900.00 asha=Rs 300.00 bala=Rs 200.00 chitra=Rs 100.00 dev=Rs 300.00
#4 Scuba (percent) paid by dev Rs 4000.00 asha=Rs 1600.00 bala=Rs 400.00 chitra=Rs 400.00 dev=Rs 1600.00
#5 Groceries (shares 2:1:1) paid by asha Rs 1000.00 asha=Rs 500.00 bala=Rs 250.00 chitra=Rs 250.00
Net balance per person (positive = the group owes them)
asha Rs 7566.66
bala -Rs 3783.33
chitra -Rs 2883.33
dev -Rs 900.00
Detailed debts, netted pair by pair: 6 payments
bala pays asha Rs 3216.66
chitra pays asha Rs 2950.00
dev pays asha Rs 1400.00
bala pays chitra Rs 166.67
bala pays dev Rs 400.00
chitra pays dev Rs 100.00
Simplified debts (greedy): 3 payments
bala pays asha Rs 3783.33
chitra pays asha Rs 2883.33
dev pays asha Rs 900.00
+14
View File
@@ -0,0 +1,14 @@
Why paise in a long, and why largest remainder
==============================================
double: 0.1 + 0.2 = 0.30000000000000004
double: ten times 0.10 = 0.9999999999999999
long, plain division: 10000 paise / 3 = 3333 each; three of them make 9999 paise
one paisa has vanished: 1
largest remainder, Rs 100.00 in 3 equal parts: [3334, 3333, 3333] sum 10000
largest remainder, 10 paise in 3 equal parts: [4, 3, 3] sum 10
largest remainder, 33.33% / 33.33% / 33.34%: [3333, 3333, 3334] sum 10000
largest remainder, shares 2:1:1 of Rs 1000.00: [50000, 25000, 25000] sum 100000
largest remainder, Rs 100.00 in 7 equal parts: [1429, 1429, 1429, 1429, 1428, 1428, 1428] sum 10000
@@ -0,0 +1,7 @@
Seeded property check: 200000 random divisions
==============================================
trials: 200000
every trial: shares add up to the total exactly
every share: equal to the exact amount rounded down, or one paisa more
largest gap above the rounded-down amount: 1 paisa
+16
View File
@@ -0,0 +1,16 @@
Bad input is rejected before it touches the ledger
==================================================
exact amounts too small -> InvalidSplitException: exact amounts add up to Rs 90.00 but the expense is Rs 100.00
percentages add up to 99.99 -> InvalidSplitException: percentages add up to 99.99 but must add up to 100
percentage with 3 decimal places -> InvalidSplitException: percent for asha has more than 2 decimal places: 33.333
zero shares -> InvalidSplitException: shares for bala must be positive
same person listed twice -> InvalidSplitException: duplicate participant in [asha, asha]
nobody to split with -> InvalidSplitException: an equal split needs at least one participant
participant outside the group -> IllegalArgumentException: esha is not a member of group Goa trip
payer outside the group -> IllegalArgumentException: esha is not a member of group Goa trip
zero-rupee expense -> IllegalArgumentException: an expense must be positive, got Rs 0.00
paying yourself -> IllegalArgumentException: asha cannot pay themselves
amount with three decimals -> IllegalArgumentException: not a whole number of paise: 10.005
After eleven rejected requests: 5 expenses, balances unchanged = true
+16
View File
@@ -0,0 +1,16 @@
Simplifying debts: pairwise vs greedy vs exact
==============================================
Goa trip: 6 pairwise payments, 3 greedy, 3 exact
Balances (Rs): a +4, b +3, c +3, d -4, e -6
greedy: 4 payments
e pays a Rs 4.00
d pays b Rs 3.00
e pays c Rs 2.00
d pays c Rs 1.00
exact: 3 payments
e pays b Rs 3.00
e pays c Rs 3.00
d pays a Rs 4.00
why: {a, d} cancel exactly (+4 -4) and {b, c, e} cancel exactly (+3 +3 -6), so two separate groups need 1 + 2 = 3 payments
+9
View File
@@ -0,0 +1,9 @@
1500 seeded random zero-sum balance sets, up to 9 people
========================================================
cases: 1500
every case: both simplifiers leave every balance at exactly zero
every case: greedy uses at most (people with a balance) - 1 payments
every case: the exact simplifier's count equals an independent backtracking search
cases where greedy used more payments than exact: 448 of 1500
largest difference: 2 payment(s)
+7
View File
@@ -0,0 +1,7 @@
Exact search cost (timing dependent: figures differ from run to run)
====================================================================
people 10: exact 9 payments in about 4 ms, greedy 9 payments in about 32 microseconds
people 14: exact 12 payments in about 18 ms, greedy 13 payments in about 29 microseconds
people 18: exact 15 payments in about 46 ms, greedy 17 payments in about 141 microseconds
people 20: exact 17 payments in about 97 ms, greedy 18 payments in about 44 microseconds
+45
View File
@@ -0,0 +1,45 @@
Recording real payments against the ledger
==========================================
Before settling
asha Rs 7566.66
bala -Rs 3783.33
chitra -Rs 2883.33
dev -Rs 900.00
After bala pays asha Rs 3783.33
asha Rs 3783.33
bala Rs 0.00
chitra -Rs 2883.33
dev -Rs 900.00
pair view after paying the net amount (asha-bala flips direction, because bala paid more than he owed asha directly):
asha pays bala Rs 566.67
chitra pays asha Rs 2950.00
dev pays asha Rs 1400.00
bala pays chitra Rs 166.67
bala pays dev Rs 400.00
chitra pays dev Rs 100.00
After dev pays asha Rs 1000.00 (Rs 100.00 more than dev owes)
asha Rs 2783.33
bala Rs 0.00
chitra -Rs 2883.33
dev Rs 100.00
Now chitra and dev follow the simplified plan
chitra pays asha Rs 2783.33
chitra pays dev Rs 100.00
After the plan
asha Rs 0.00
bala Rs 0.00
chitra Rs 0.00
dev Rs 0.00
net balances all zero: true
pair view still lists 5 debts, because the plan paid net amounts, not the original pairs:
asha pays bala Rs 566.67
chitra pays asha Rs 166.67
dev pays asha Rs 400.00
bala pays chitra Rs 166.67
bala pays dev Rs 400.00
each person's pair debts add up to their net balance: true
+7
View File
@@ -0,0 +1,7 @@
The ledger is derived: replaying the log rebuilds it exactly
============================================================
expenses replayed: 5
settlements replayed: 1
net balances equal: true
pairwise debts equal: true
+7
View File
@@ -0,0 +1,7 @@
Eight threads adding expenses to one group
==========================================
expenses added: 40000 (expected 40000)
distinct expense ids: 40000, highest id: 40000
net balances add up to zero: true
replaying the log gives the same balances: true
@@ -0,0 +1,6 @@
Control: the same idea without a lock (timing dependent: the figure differs every run)
======================================================================================
expected total: 1600000
actual total: 740725
updates lost: 859275 (always zero or more, and usually well above zero)
+25
View File
@@ -0,0 +1,25 @@
Pitfalls that look fine until they are not
==========================================
1. new BigDecimal(33.33) = 33.3299999999999982946974341757595539093017578125
new BigDecimal("33.33") = 33.33
the split rejects the double-built value: percent for asha has more than 2 decimal places: 33.3299999999999982946974341757595539093017578125
2. 3000 dinners of Rs 100.00 between asha, bala and chitra
always the same order: asha Rs 100020.00, bala Rs 99990.00, chitra Rs 99990.00
rotating tie offset: asha Rs 100000.00, bala Rs 100000.00, chitra Rs 100000.00
3. asha pays Rs 600.00 for a gift but is not in the split
asha Rs 600.00
bala -Rs 300.00
chitra -Rs 300.00
4. default fraction digits: INR 2, JPY 0, KWD 3
5. an expense of Rs 0.01 split three ways
asha Rs 0.00
bala Rs 0.00
chitra Rs 0.00
debts: []
6. simplifying balances that do not add up to zero: balances do not add up to zero: the sum is Rs 0.01
+64
View File
@@ -0,0 +1,64 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ankurm.interviewlab</groupId>
<artifactId>splitwise</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>
<name>java-interview-lab :: splitwise</name>
<description>
Runnable companion code for ankurm.com's "Low-Level Design: Splitwise (Expense Sharing) in Java" article: split strategies,
exact paise arithmetic, a derived ledger and debt simplification (greedy and exact).
</description>
<properties>
<maven.compiler.release>25</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<junit.version>6.1.3</junit.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.junit</groupId>
<artifactId>junit-bom</artifactId>
<version>${junit.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-launcher</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.14.0</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.6.0</version>
<configuration>
<argLine>-Xmx512m -Duser.timezone=UTC -Dfile.encoding=UTF-8</argLine>
</configuration>
</plugin>
</plugins>
</build>
</project>
+9
View File
@@ -0,0 +1,9 @@
#!/usr/bin/env bash
# Regenerates every file in output/. Needs JDK 25 and Maven. The first Maven run must be online.
# Every file is written by a JUnit test that asserts the same numbers it prints, so the figures
# in the article are assertions: they fail the build the moment they stop being true.
set -euo pipefail
cd "$(dirname "$0")/.."
mkdir -p output
mvn -B -q -T1 test
echo "done:"; ls -1 output
@@ -0,0 +1,61 @@
package com.ankurm.interviewlab.splitwise;
import java.util.Arrays;
import java.util.Comparator;
/**
* Divides a whole number of paise in proportion to integer weights so that the parts add up to exactly the total.
* This is the largest remainder (Hamilton) method: give everyone the rounded-down share, then hand the leftover
* paise, one each, to the people whose exact share had the biggest fractional part.
*/
public final class Apportion {
private Apportion() {
}
/**
* @param total paise to divide, zero or more
* @param weights one non-negative weight per person; at least one must be positive
* @param tieOffset which index wins a tie for a leftover paisa first (indexes after it follow, wrapping around)
*/
public static long[] split(long total, long[] weights, int tieOffset) {
if (total < 0) {
throw new IllegalArgumentException("total must not be negative: " + total);
}
long weightSum = 0;
for (long w : weights) {
if (w < 0) {
throw new IllegalArgumentException("weights must not be negative");
}
weightSum = Math.addExact(weightSum, w);
}
if (weightSum == 0) {
throw new IllegalArgumentException("at least one weight must be positive");
}
int n = weights.length;
long[] parts = new long[n];
long[] remainder = new long[n];
long given = 0;
for (int i = 0; i < n; i++) {
long scaled = Math.multiplyExact(total, weights[i]);
parts[i] = scaled / weightSum;
remainder[i] = scaled % weightSum;
given += parts[i];
}
int leftover = (int) (total - given);
Integer[] order = new Integer[n];
for (int i = 0; i < n; i++) {
order[i] = i;
}
Arrays.sort(order, Comparator
.comparingLong((Integer i) -> remainder[i]).reversed()
.thenComparingInt(i -> Math.floorMod(i - tieOffset, n)));
for (int k = 0; k < leftover; k++) {
parts[order[k]]++;
}
return parts;
}
public static long[] split(long total, long[] weights) {
return split(total, weights, 0);
}
}
@@ -0,0 +1,11 @@
package com.ankurm.interviewlab.splitwise;
import java.util.List;
import java.util.Map;
/** Turns net balances into a short list of payments that leaves everybody at zero. */
public interface DebtSimplifier {
/** @param net user id to net paise (positive: is owed money); must add up to zero */
List<Transfer> simplify(Map<String, Long> net);
}
@@ -0,0 +1,46 @@
package com.ankurm.interviewlab.splitwise;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/** Everyone listed pays the same, give or take one paisa. */
public final class EqualSplit implements SplitStrategy {
private final List<String> participants;
private final int tieOffset;
public EqualSplit(List<String> participants) {
this(participants, 0);
}
/** {@code tieOffset} picks who is charged the extra paisa first; rotate it to keep a long series fair. */
public EqualSplit(List<String> participants, int tieOffset) {
if (participants.isEmpty()) {
throw new InvalidSplitException("an equal split needs at least one participant");
}
if (new LinkedHashSet<>(participants).size() != participants.size()) {
throw new InvalidSplitException("duplicate participant in " + participants);
}
this.participants = List.copyOf(participants);
this.tieOffset = tieOffset;
}
@Override
public Set<String> participants() {
return new LinkedHashSet<>(participants);
}
@Override
public Map<String, Long> split(long totalPaise) {
long[] weights = new long[participants.size()];
java.util.Arrays.fill(weights, 1);
long[] parts = Apportion.split(totalPaise, weights, tieOffset);
Map<String, Long> shares = new LinkedHashMap<>();
for (int i = 0; i < parts.length; i++) {
shares.put(participants.get(i), parts[i]);
}
return shares;
}
}
@@ -0,0 +1,38 @@
package com.ankurm.interviewlab.splitwise;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
/** The payer states each person's amount; the amounts must add up to the expense exactly. */
public final class ExactSplit implements SplitStrategy {
private final Map<String, Long> amounts;
public ExactSplit(Map<String, Long> amounts) {
if (amounts.isEmpty()) {
throw new InvalidSplitException("an exact split needs at least one participant");
}
amounts.forEach((user, paise) -> {
if (paise < 0) {
throw new InvalidSplitException("amount for " + user + " must not be negative");
}
});
this.amounts = new LinkedHashMap<>(amounts);
}
@Override
public Set<String> participants() {
return new LinkedHashSet<>(amounts.keySet());
}
@Override
public Map<String, Long> split(long totalPaise) {
long sum = amounts.values().stream().mapToLong(Long::longValue).sum();
if (sum != totalPaise) {
throw new InvalidSplitException("exact amounts add up to " + Money.format(sum)
+ " but the expense is " + Money.format(totalPaise));
}
return new LinkedHashMap<>(amounts);
}
}
@@ -0,0 +1,23 @@
package com.ankurm.interviewlab.splitwise;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* One thing somebody paid for. {@code shares} says what each person owes for it, in paise, and always adds up to the total.
* The payer need not appear in {@code shares} (somebody can pay for other people entirely).
*/
public record Expense(long id, String description, String paidBy, long totalPaise, Map<String, Long> shares) {
public Expense {
if (totalPaise <= 0) {
throw new IllegalArgumentException("an expense must be positive, got " + Money.format(totalPaise));
}
shares = Collections.unmodifiableMap(new LinkedHashMap<>(shares));
long sum = shares.values().stream().mapToLong(Long::longValue).sum();
if (sum != totalPaise) {
throw new IllegalArgumentException("shares add up to " + Money.format(sum) + " but the expense is " + Money.format(totalPaise));
}
}
}
@@ -0,0 +1,51 @@
package com.ankurm.interviewlab.splitwise;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
/**
* Repeatedly makes the biggest debtor pay the biggest creditor as much as they can. Every payment settles at least one
* person completely, so n people with non-zero balances need at most n - 1 payments. Fast (O(n log n)) but not always the minimum.
*/
public final class GreedyDebtSimplifier implements DebtSimplifier {
private record Balance(String user, long paise) {
}
private static final Comparator<Balance> BIGGEST_FIRST =
Comparator.comparingLong(Balance::paise).reversed().thenComparing(Balance::user);
@Override
public List<Transfer> simplify(Map<String, Long> net) {
long sum = net.values().stream().mapToLong(Long::longValue).sum();
if (sum != 0) {
throw new IllegalArgumentException("balances do not add up to zero: the sum is " + Money.format(sum));
}
PriorityQueue<Balance> creditors = new PriorityQueue<>(BIGGEST_FIRST);
PriorityQueue<Balance> debtors = new PriorityQueue<>(BIGGEST_FIRST); // paise stored as the positive amount owed
net.forEach((user, paise) -> {
if (paise > 0) {
creditors.add(new Balance(user, paise));
} else if (paise < 0) {
debtors.add(new Balance(user, -paise));
}
});
List<Transfer> transfers = new ArrayList<>();
while (!creditors.isEmpty() && !debtors.isEmpty()) {
Balance creditor = creditors.poll();
Balance debtor = debtors.poll();
long pay = Math.min(creditor.paise(), debtor.paise());
transfers.add(new Transfer(debtor.user(), creditor.user(), pay));
if (creditor.paise() > pay) {
creditors.add(new Balance(creditor.user(), creditor.paise() - pay));
}
if (debtor.paise() > pay) {
debtors.add(new Balance(debtor.user(), debtor.paise() - pay));
}
}
return transfers;
}
}
@@ -0,0 +1,91 @@
package com.ankurm.interviewlab.splitwise;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* A set of people who share expenses. Every change goes through a synchronized method, so the ledger can never be seen
* half-updated: an expense is checked, divided and applied as one step.
*/
public final class Group {
private final String id;
private final String name;
private final Set<String> members;
private final Ledger ledger = new Ledger();
private final List<Expense> expenses = new ArrayList<>();
private final List<Transfer> settlements = new ArrayList<>();
private long nextExpenseId = 1;
public Group(String id, String name, Set<String> members) {
this.id = id;
this.name = name;
this.members = new LinkedHashSet<>(members);
}
public String id() {
return id;
}
public String name() {
return name;
}
public synchronized Expense addExpense(String description, String paidBy, long totalPaise, SplitStrategy strategy) {
requireMember(paidBy);
strategy.participants().forEach(this::requireMember);
Map<String, Long> shares = strategy.split(totalPaise);
Expense expense = new Expense(nextExpenseId, description, paidBy, totalPaise, shares);
nextExpenseId++;
ledger.apply(expense);
expenses.add(expense);
return expense;
}
/** Records that {@code from} really paid {@code to} outside the app. */
public synchronized Transfer settle(String from, String to, long paise) {
requireMember(from);
requireMember(to);
Transfer transfer = new Transfer(from, to, paise);
ledger.apply(transfer);
settlements.add(transfer);
return transfer;
}
/** Net balance for every member, including members with nothing yet. */
public synchronized Map<String, Long> balances() {
Map<String, Long> net = ledger.net();
Map<String, Long> result = new LinkedHashMap<>();
members.forEach(m -> result.put(m, net.getOrDefault(m, 0L)));
return result;
}
public synchronized List<Transfer> pairwiseDebts() {
return ledger.pairwiseDebts();
}
public synchronized List<Transfer> simplifiedDebts(DebtSimplifier simplifier) {
return simplifier.simplify(ledger.net());
}
public synchronized List<Expense> expenses() {
return List.copyOf(expenses);
}
public synchronized List<Transfer> settlements() {
return List.copyOf(settlements);
}
public synchronized boolean isBalanced() {
return ledger.isBalanced();
}
private void requireMember(String user) {
if (!members.contains(user)) {
throw new IllegalArgumentException(user + " is not a member of group " + name);
}
}
}
@@ -0,0 +1,8 @@
package com.ankurm.interviewlab.splitwise;
/** Thrown when the numbers describing a split cannot produce a valid division of the expense. */
public class InvalidSplitException extends IllegalArgumentException {
public InvalidSplitException(String message) {
super(message);
}
}
@@ -0,0 +1,64 @@
package com.ankurm.interviewlab.splitwise;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
/**
* Who owes what, derived by applying expenses and settlements one at a time. It keeps two views of the same facts:
* a net balance per person (positive: the group owes them) and a signed balance per pair of people.
* Not thread-safe by itself; {@link Group} serialises access.
*/
public final class Ledger {
private final Map<String, Long> net = new TreeMap<>();
private final Map<String, Long> pair = new TreeMap<>(); // key "a|b" with a < b; positive means a owes b
public void apply(Expense e) {
net.merge(e.paidBy(), e.totalPaise(), Long::sum);
e.shares().forEach((user, share) -> {
net.merge(user, -share, Long::sum);
if (!user.equals(e.paidBy()) && share > 0) {
owes(user, e.paidBy(), share);
}
});
}
public void apply(Transfer t) {
net.merge(t.from(), t.paise(), Long::sum);
net.merge(t.to(), -t.paise(), Long::sum);
owes(t.from(), t.to(), -t.paise());
}
private void owes(String debtor, String creditor, long paise) {
if (debtor.compareTo(creditor) < 0) {
pair.merge(debtor + "|" + creditor, paise, Long::sum);
} else {
pair.merge(creditor + "|" + debtor, -paise, Long::sum);
}
}
/** Net balance per person: what they are owed (positive) or owe (negative). */
public Map<String, Long> net() {
return new LinkedHashMap<>(net);
}
/** Every pair that still owes something, netted so each pair appears once: this is the "detailed debts" view. */
public List<Transfer> pairwiseDebts() {
List<Transfer> debts = new ArrayList<>();
pair.forEach((key, value) -> {
if (value == 0) {
return;
}
String[] ab = key.split("\\|");
debts.add(value > 0 ? new Transfer(ab[0], ab[1], value) : new Transfer(ab[1], ab[0], -value));
});
return debts;
}
/** The invariant everything rests on: money is only moved, never created, so the net balances add up to zero. */
public boolean isBalanced() {
return net.values().stream().mapToLong(Long::longValue).sum() == 0;
}
}
@@ -0,0 +1,29 @@
package com.ankurm.interviewlab.splitwise;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Locale;
/**
* Every amount in this module is a whole number of paise held in a {@code long}. This class only converts to and from text,
* so the arithmetic everywhere else is exact integer arithmetic.
*/
public final class Money {
private Money() {
}
/** "100.00" becomes 10000. Text with more than two decimal places is rejected rather than rounded. */
public static long ofRupees(String text) {
try {
return new BigDecimal(text).setScale(2, RoundingMode.UNNECESSARY).movePointRight(2).longValueExact();
} catch (ArithmeticException e) {
throw new IllegalArgumentException("not a whole number of paise: " + text, e);
}
}
/** 3334 becomes "Rs 33.34"; negative amounts keep the sign in front. */
public static String format(long paise) {
long abs = Math.abs(paise);
return String.format(Locale.ROOT, "%sRs %d.%02d", paise < 0 ? "-" : "", abs / 100, abs % 100);
}
}
@@ -0,0 +1,68 @@
package com.ankurm.interviewlab.splitwise;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* Finds the true minimum number of payments. A group of people whose balances add up to zero can settle among themselves
* with (size - 1) payments, so the minimum is (people) minus (the most zero-sum groups the people can be split into).
* Finding that split is a subset-sum style problem, solved here by dynamic programming over all subsets: O(2^n * n),
* so it is limited to {@value #MAX_PEOPLE} people with a non-zero balance.
*/
public final class OptimalDebtSimplifier implements DebtSimplifier {
public static final int MAX_PEOPLE = 20;
private final DebtSimplifier insideAGroup = new GreedyDebtSimplifier();
@Override
public List<Transfer> simplify(Map<String, Long> net) {
long total = net.values().stream().mapToLong(Long::longValue).sum();
if (total != 0) {
throw new IllegalArgumentException("balances do not add up to zero: the sum is " + Money.format(total));
}
List<String> users = new ArrayList<>(net.keySet().stream().filter(u -> net.get(u) != 0).sorted().toList());
int n = users.size();
if (n == 0) {
return List.of();
}
if (n > MAX_PEOPLE) {
throw new IllegalArgumentException("exact search is limited to " + MAX_PEOPLE + " people, got " + n);
}
int full = (1 << n) - 1;
long[] sum = new long[full + 1];
int[] zeroGroups = new int[full + 1];
byte[] last = new byte[full + 1];
for (int mask = 1; mask <= full; mask++) {
int low = Integer.numberOfTrailingZeros(mask);
sum[mask] = sum[mask & (mask - 1)] + net.get(users.get(low));
int best = -1;
for (int i = 0; i < n; i++) {
if ((mask & (1 << i)) != 0 && zeroGroups[mask ^ (1 << i)] > best) {
best = zeroGroups[mask ^ (1 << i)];
last[mask] = (byte) i;
}
}
zeroGroups[mask] = best + (sum[mask] == 0 ? 1 : 0);
}
// Rebuild the best ordering, then cut it wherever the running total returns to zero.
List<Integer> order = new ArrayList<>();
for (int mask = full; mask != 0; mask ^= 1 << last[mask]) {
order.add(0, (int) last[mask]);
}
List<Transfer> transfers = new ArrayList<>();
Map<String, Long> group = new LinkedHashMap<>();
long running = 0;
for (int i : order) {
String user = users.get(i);
group.put(user, net.get(user));
running += net.get(user);
if (running == 0) {
transfers.addAll(insideAGroup.simplify(group));
group = new LinkedHashMap<>();
}
}
return transfers;
}
}
@@ -0,0 +1,55 @@
package com.ankurm.interviewlab.splitwise;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
/** Each person pays a percentage, with at most two decimal places; the percentages must add up to exactly 100. */
public final class PercentSplit implements SplitStrategy {
private final Map<String, BigDecimal> percents;
public PercentSplit(Map<String, BigDecimal> percents) {
if (percents.isEmpty()) {
throw new InvalidSplitException("a percent split needs at least one participant");
}
BigDecimal sum = BigDecimal.ZERO;
for (Map.Entry<String, BigDecimal> e : percents.entrySet()) {
BigDecimal p = e.getValue();
if (p.signum() < 0) {
throw new InvalidSplitException("percent for " + e.getKey() + " must not be negative");
}
if (p.stripTrailingZeros().scale() > 2) {
throw new InvalidSplitException("percent for " + e.getKey()
+ " has more than 2 decimal places: " + p.toPlainString());
}
sum = sum.add(p);
}
if (sum.compareTo(BigDecimal.valueOf(100)) != 0) {
throw new InvalidSplitException("percentages add up to " + sum.toPlainString() + " but must add up to 100");
}
this.percents = new LinkedHashMap<>(percents);
}
@Override
public Set<String> participants() {
return new LinkedHashSet<>(percents.keySet());
}
@Override
public Map<String, Long> split(long totalPaise) {
String[] users = percents.keySet().toArray(new String[0]);
long[] basisPoints = new long[users.length];
for (int i = 0; i < users.length; i++) {
basisPoints[i] = percents.get(users[i]).setScale(2, RoundingMode.UNNECESSARY).movePointRight(2).longValueExact();
}
long[] parts = Apportion.split(totalPaise, basisPoints);
Map<String, Long> shares = new LinkedHashMap<>();
for (int i = 0; i < users.length; i++) {
shares.put(users[i], parts[i]);
}
return shares;
}
}
@@ -0,0 +1,43 @@
package com.ankurm.interviewlab.splitwise;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
/** Each person owns a number of shares ("2 nights, 1 night"); the cost is divided in proportion. */
public final class ShareSplit implements SplitStrategy {
private final Map<String, Integer> shares;
public ShareSplit(Map<String, Integer> shares) {
if (shares.isEmpty()) {
throw new InvalidSplitException("a share split needs at least one participant");
}
shares.forEach((user, n) -> {
if (n <= 0) {
throw new InvalidSplitException("shares for " + user + " must be positive");
}
});
this.shares = new LinkedHashMap<>(shares);
}
@Override
public Set<String> participants() {
return new LinkedHashSet<>(shares.keySet());
}
@Override
public Map<String, Long> split(long totalPaise) {
String[] users = shares.keySet().toArray(new String[0]);
long[] weights = new long[users.length];
for (int i = 0; i < users.length; i++) {
weights[i] = shares.get(users[i]);
}
long[] parts = Apportion.split(totalPaise, weights);
Map<String, Long> result = new LinkedHashMap<>();
for (int i = 0; i < users.length; i++) {
result.put(users[i], parts[i]);
}
return result;
}
}
@@ -0,0 +1,14 @@
package com.ankurm.interviewlab.splitwise;
import java.util.Map;
import java.util.Set;
/** One way of dividing an expense. Implementations are small immutable values, so a group can accept any of them. */
public interface SplitStrategy {
/** Everyone who owes a share, in the order the shares are reported. */
Set<String> participants();
/** Returns user id to share in paise. The shares add up to exactly {@code totalPaise}. */
Map<String, Long> split(long totalPaise);
}
@@ -0,0 +1,43 @@
package com.ankurm.interviewlab.splitwise;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
/** The front door: register people, create groups, find them again. Everything else happens on {@link Group}. */
public final class SplitwiseService {
private final Map<String, User> users = new LinkedHashMap<>();
private final Map<String, Group> groups = new LinkedHashMap<>();
public synchronized User registerUser(String id, String name) {
if (users.containsKey(id)) {
throw new IllegalArgumentException("user id already taken: " + id);
}
User user = new User(id, name);
users.put(id, user);
return user;
}
public synchronized Group createGroup(String id, String name, List<String> memberIds) {
memberIds.forEach(m -> {
if (!users.containsKey(m)) {
throw new IllegalArgumentException("unknown user: " + m);
}
});
if (groups.containsKey(id)) {
throw new IllegalArgumentException("group id already taken: " + id);
}
Group group = new Group(id, name, new LinkedHashSet<>(memberIds));
groups.put(id, group);
return group;
}
public synchronized Group group(String id) {
Group group = groups.get(id);
if (group == null) {
throw new IllegalArgumentException("unknown group: " + id);
}
return group;
}
}
@@ -0,0 +1,19 @@
package com.ankurm.interviewlab.splitwise;
/** {@code from} pays {@code to} this many paise. Used both for recorded settlements and for suggested simplified payments. */
public record Transfer(String from, String to, long paise) {
public Transfer {
if (paise <= 0) {
throw new IllegalArgumentException("a transfer must be positive, got " + Money.format(paise));
}
if (from.equals(to)) {
throw new IllegalArgumentException(from + " cannot pay themselves");
}
}
@Override
public String toString() {
return from + " pays " + to + " " + Money.format(paise);
}
}
@@ -0,0 +1,5 @@
package com.ankurm.interviewlab.splitwise;
/** A person. The id is what every other class refers to; the name is only for display. */
public record User(String id, String name) {
}
@@ -0,0 +1,109 @@
package com.ankurm.interviewlab.splitwise;
import com.ankurm.interviewlab.splitwise.support.Transcript;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SplittableRandom;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
class ConcurrencyTest {
@Test
void manyThreadsAddingExpensesKeepTheLedgerBalanced() throws Exception {
Transcript out = Transcript.start("06-concurrency.txt", "Eight threads adding expenses to one group");
List<String> people = List.of("p0", "p1", "p2", "p3", "p4", "p5");
Group group = new Group("g", "stress", new java.util.LinkedHashSet<>(people));
int threads = 8;
int perThread = 5000;
CountDownLatch start = new CountDownLatch(1);
List<Thread> workers = new ArrayList<>();
AtomicReference<Throwable> failure = new AtomicReference<>();
for (int t = 0; t < threads; t++) {
long seed = 100 + t;
Thread worker = new Thread(() -> {
try {
start.await();
SplittableRandom random = new SplittableRandom(seed);
for (int i = 0; i < perThread; i++) {
String payer = people.get(random.nextInt(people.size()));
List<String> sharers = new ArrayList<>(people);
java.util.Collections.shuffle(sharers, new java.util.Random(random.nextLong()));
sharers = sharers.subList(0, 1 + random.nextInt(people.size()));
group.addExpense("e", payer, 1 + random.nextInt(500_000), new EqualSplit(sharers));
}
} catch (Throwable e) {
failure.set(e);
}
});
workers.add(worker);
worker.start();
}
start.countDown();
for (Thread w : workers) {
w.join();
}
assertEquals(null, failure.get());
List<Expense> expenses = group.expenses();
Set<Long> ids = new HashSet<>();
expenses.forEach(e -> ids.add(e.id()));
Ledger replay = new Ledger();
expenses.forEach(replay::apply);
out.line("expenses added: " + expenses.size() + " (expected " + threads * perThread + ")");
out.line("distinct expense ids: " + ids.size() + ", highest id: " + expenses.stream().mapToLong(Expense::id).max().orElse(0));
out.line("net balances add up to zero: " + group.isBalanced());
out.line("replaying the log gives the same balances: " + replay.net().equals(Map.copyOf(group.balances())));
assertEquals(threads * perThread, expenses.size());
assertEquals(threads * perThread, ids.size());
assertEquals(threads * perThread, expenses.stream().mapToLong(Expense::id).max().orElse(0));
assertTrue(group.isBalanced());
assertEquals(Map.copyOf(group.balances()), Map.copyOf(replay.net()));
out.flush();
}
@Test
void controlAnUnsynchronisedMapLosesUpdates() throws Exception {
Transcript out = Transcript.start("06b-concurrency-control.txt", "Control: the same idea without a lock (timing dependent: the figure differs every run)");
Map<String, Long> unsafe = new HashMap<>();
int threads = 8;
int perThread = 200_000;
CountDownLatch start = new CountDownLatch(1);
List<Thread> workers = new ArrayList<>();
for (int t = 0; t < threads; t++) {
Thread worker = new Thread(() -> {
try {
start.await();
for (int i = 0; i < perThread; i++) {
unsafe.merge("asha", 1L, Long::sum);
}
} catch (Throwable ignored) {
// a corrupted HashMap may throw; the point is that the total is wrong
}
});
workers.add(worker);
worker.start();
}
start.countDown();
for (Thread w : workers) {
w.join();
}
long expected = (long) threads * perThread;
long actual = unsafe.getOrDefault("asha", 0L);
out.line("expected total: " + expected);
out.line("actual total: " + actual);
out.line("updates lost: " + (expected - actual) + " (always zero or more, and usually well above zero)");
assertTrue(actual <= expected);
out.flush();
}
}
@@ -0,0 +1,54 @@
package com.ankurm.interviewlab.splitwise;
import com.ankurm.interviewlab.splitwise.support.Fixtures;
import com.ankurm.interviewlab.splitwise.support.Transcript;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
class HappyPathTest {
@Test
void goaTripBalancesAndDebts() {
Group trip = Fixtures.goaTrip();
Transcript out = Transcript.start("01-happy-path.txt", "Four friends, five expenses, four split strategies");
out.line("Expenses (shares in paise-exact rupees)");
for (Expense e : trip.expenses()) {
out.line(Fixtures.describe(e));
}
// Shares that need a rounding decision: Rs 100.00 between three people.
assertEquals(Map.of("asha", 3334L, "bala", 3333L, "chitra", 3333L), trip.expenses().get(1).shares());
assertEquals(Map.of("asha", 160000L, "bala", 40000L, "chitra", 40000L, "dev", 160000L), trip.expenses().get(3).shares());
assertEquals(Map.of("asha", 50000L, "bala", 25000L, "chitra", 25000L), trip.expenses().get(4).shares());
Map<String, Long> net = trip.balances();
out.blank().line("Net balance per person (positive = the group owes them)").line(Fixtures.describe(net));
assertEquals(756666L, net.get("asha"));
assertEquals(-378333L, net.get("bala"));
assertEquals(-288333L, net.get("chitra"));
assertEquals(-90000L, net.get("dev"));
assertEquals(0L, net.values().stream().mapToLong(Long::longValue).sum());
assertTrue(trip.isBalanced());
List<Transfer> pairwise = trip.pairwiseDebts();
out.blank().line("Detailed debts, netted pair by pair: " + pairwise.size() + " payments");
pairwise.forEach(t -> out.line(" " + t));
assertEquals(6, pairwise.size());
List<Transfer> simple = trip.simplifiedDebts(new GreedyDebtSimplifier());
out.blank().line("Simplified debts (greedy): " + simple.size() + " payments");
simple.forEach(t -> out.line(" " + t));
assertEquals(3, simple.size());
assertEquals(List.of(
new Transfer("bala", "asha", 378333L),
new Transfer("chitra", "asha", 288333L),
new Transfer("dev", "asha", 90000L)), simple);
out.flush();
}
}
@@ -0,0 +1,91 @@
package com.ankurm.interviewlab.splitwise;
import com.ankurm.interviewlab.splitwise.support.Fixtures;
import com.ankurm.interviewlab.splitwise.support.Transcript;
import org.junit.jupiter.api.Test;
import java.math.BigDecimal;
import java.util.Currency;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class PitfallsTest {
@Test
void sixPitfalls() {
Transcript out = Transcript.start("07-pitfalls.txt", "Pitfalls that look fine until they are not");
// 1. A double-based percent
BigDecimal fromDouble = new BigDecimal(33.33);
out.line("1. new BigDecimal(33.33) = " + fromDouble.toPlainString());
out.line(" new BigDecimal(\"33.33\") = " + new BigDecimal("33.33").toPlainString());
InvalidSplitException e = assertThrows(InvalidSplitException.class,
() -> new PercentSplit(Map.of("asha", fromDouble, "bala", new BigDecimal("66.67"))));
out.line(" the split rejects the double-built value: " + e.getMessage());
assertEquals("percent for asha has more than 2 decimal places: " + fromDouble.toPlainString(), e.getMessage());
// 2. The extra paisa always lands on the same person
List<String> abc = List.of("asha", "bala", "chitra");
long[] fixedOrder = new long[3];
long[] rotating = new long[3];
for (int i = 0; i < 3000; i++) {
long[] a = shares(new EqualSplit(abc).split(10000L), abc);
long[] b = shares(new EqualSplit(abc, i).split(10000L), abc);
for (int k = 0; k < 3; k++) {
fixedOrder[k] += a[k];
rotating[k] += b[k];
}
}
out.blank().line("2. 3000 dinners of Rs 100.00 between asha, bala and chitra");
out.line(" always the same order: asha " + Money.format(fixedOrder[0]) + ", bala " + Money.format(fixedOrder[1]) + ", chitra " + Money.format(fixedOrder[2]));
out.line(" rotating tie offset: asha " + Money.format(rotating[0]) + ", bala " + Money.format(rotating[1]) + ", chitra " + Money.format(rotating[2]));
assertEquals(10_002_000L, fixedOrder[0]);
assertEquals(9_999_000L, fixedOrder[1]);
assertEquals(10_000_000L, rotating[0]);
assertEquals(10_000_000L, rotating[1]);
assertEquals(10_000_000L, rotating[2]);
// 3. The payer does not have to take part in the split
Group g = new Group("g", "Gift", new java.util.LinkedHashSet<>(List.of("asha", "bala", "chitra")));
g.addExpense("Gift for chitra", "asha", Money.ofRupees("600.00"), new EqualSplit(List.of("bala", "chitra")));
out.blank().line("3. asha pays Rs 600.00 for a gift but is not in the split");
out.line(indent(Fixtures.describe(g.balances())));
assertEquals(60000L, g.balances().get("asha"));
assertEquals(-30000L, g.balances().get("chitra"));
// 4. Currencies do not all have two decimals
out.blank().line("4. default fraction digits: INR " + Currency.getInstance("INR").getDefaultFractionDigits()
+ ", JPY " + Currency.getInstance("JPY").getDefaultFractionDigits()
+ ", KWD " + Currency.getInstance("KWD").getDefaultFractionDigits());
assertEquals(2, Currency.getInstance("INR").getDefaultFractionDigits());
assertEquals(0, Currency.getInstance("JPY").getDefaultFractionDigits());
assertEquals(3, Currency.getInstance("KWD").getDefaultFractionDigits());
// 5. Rounding creates a tiny amount that still needs a payment
Group h = new Group("h", "Tiny", new java.util.LinkedHashSet<>(List.of("asha", "bala", "chitra")));
h.addExpense("One paisa item", "asha", 1, new EqualSplit(List.of("asha", "bala", "chitra")));
out.blank().line("5. an expense of Rs 0.01 split three ways");
out.line(indent(Fixtures.describe(h.balances())));
out.line(" debts: " + h.pairwiseDebts());
assertEquals(0L, h.balances().get("asha"));
assertEquals(0, h.pairwiseDebts().size());
// 6. Balances that do not add up are refused, not silently simplified
IllegalArgumentException bad = assertThrows(IllegalArgumentException.class,
() -> new GreedyDebtSimplifier().simplify(Map.of("asha", 100L, "bala", -99L)));
out.blank().line("6. simplifying balances that do not add up to zero: " + bad.getMessage());
assertEquals("balances do not add up to zero: the sum is Rs 0.01", bad.getMessage());
out.flush();
}
private static long[] shares(Map<String, Long> split, List<String> order) {
return order.stream().mapToLong(split::get).toArray();
}
private static String indent(String text) {
return " " + text.replace("\n", "\n ");
}
}
@@ -0,0 +1,92 @@
package com.ankurm.interviewlab.splitwise;
import com.ankurm.interviewlab.splitwise.support.Transcript;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.SplittableRandom;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
class RoundingTest {
@Test
void whyNotDoubleOrTruncation() {
Transcript out = Transcript.start("02-rounding.txt", "Why paise in a long, and why largest remainder");
double a = 0.1 + 0.2;
double tenTimes = 0;
for (int i = 0; i < 10; i++) {
tenTimes += 0.10;
}
out.line("double: 0.1 + 0.2 = " + a);
out.line("double: ten times 0.10 = " + tenTimes);
assertNotEquals(0.3, a);
assertNotEquals(1.0, tenTimes);
long total = Money.ofRupees("100.00");
long truncated = total / 3;
out.blank().line("long, plain division: " + total + " paise / 3 = " + truncated + " each; three of them make " + (truncated * 3) + " paise");
out.line("one paisa has vanished: " + (total - truncated * 3));
assertEquals(1, total - truncated * 3);
long[] equal = Apportion.split(total, new long[]{1, 1, 1});
out.blank().line("largest remainder, Rs 100.00 in 3 equal parts: " + Arrays.toString(equal) + " sum " + sum(equal));
assertArrayEquals(new long[]{3334, 3333, 3333}, equal);
long[] tiny = Apportion.split(10, new long[]{1, 1, 1});
out.line("largest remainder, 10 paise in 3 equal parts: " + Arrays.toString(tiny) + " sum " + sum(tiny));
assertArrayEquals(new long[]{4, 3, 3}, tiny);
long[] weighted = Apportion.split(Money.ofRupees("100.00"), new long[]{3333, 3333, 3334});
out.line("largest remainder, 33.33% / 33.33% / 33.34%: " + Arrays.toString(weighted) + " sum " + sum(weighted));
assertArrayEquals(new long[]{3333, 3333, 3334}, weighted);
long[] shares = Apportion.split(Money.ofRupees("1000.00"), new long[]{2, 1, 1});
out.line("largest remainder, shares 2:1:1 of Rs 1000.00: " + Arrays.toString(shares) + " sum " + sum(shares));
assertArrayEquals(new long[]{50000, 25000, 25000}, shares);
long[] seven = Apportion.split(Money.ofRupees("100.00"), new long[]{1, 1, 1, 1, 1, 1, 1});
out.line("largest remainder, Rs 100.00 in 7 equal parts: " + Arrays.toString(seven) + " sum " + sum(seven));
assertEquals(10000, sum(seven));
out.flush();
}
@Test
void sharesAlwaysAddUpAndStayWithinOnePaisaOfExact() {
Transcript out = Transcript.start("02b-rounding-property.txt", "Seeded property check: 200000 random divisions");
SplittableRandom random = new SplittableRandom(2026);
int trials = 200_000;
long worstGap = 0;
for (int t = 0; t < trials; t++) {
int n = 1 + random.nextInt(12);
long[] weights = new long[n];
long weightSum = 0;
for (int i = 0; i < n; i++) {
weights[i] = 1 + random.nextInt(10_000);
weightSum += weights[i];
}
long total = 1 + random.nextLong(100_000_000L);
long[] parts = Apportion.split(total, weights, random.nextInt(n));
assertEquals(total, sum(parts), "shares must add up exactly");
for (int i = 0; i < n; i++) {
long floor = Math.multiplyExact(total, weights[i]) / weightSum;
assertTrue(parts[i] == floor || parts[i] == floor + 1, "share outside floor/ceil of the exact quota");
worstGap = Math.max(worstGap, parts[i] - floor);
}
}
out.line("trials: " + trials);
out.line("every trial: shares add up to the total exactly");
out.line("every share: equal to the exact amount rounded down, or one paisa more");
out.line("largest gap above the rounded-down amount: " + worstGap + " paisa");
assertEquals(1, worstGap);
out.flush();
}
private static long sum(long[] values) {
return Arrays.stream(values).sum();
}
}
@@ -0,0 +1,77 @@
package com.ankurm.interviewlab.splitwise;
import com.ankurm.interviewlab.splitwise.support.Fixtures;
import com.ankurm.interviewlab.splitwise.support.Transcript;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
class SettleUpTest {
@Test
void settlingMovesBalancesAndNeverBreaksTheInvariant() {
Group trip = Fixtures.goaTrip();
Transcript out = Transcript.start("05-settle-up.txt", "Recording real payments against the ledger");
out.line("Before settling");
out.line(Fixtures.describe(trip.balances()));
trip.settle("bala", "asha", 378333);
out.blank().line("After bala pays asha Rs 3783.33");
out.line(Fixtures.describe(trip.balances()));
assertEquals(0L, trip.balances().get("bala"));
assertEquals(378333L, trip.balances().get("asha"));
out.line("pair view after paying the net amount (asha-bala flips direction, because bala paid more than he owed asha directly):");
trip.pairwiseDebts().forEach(t -> out.line(" " + t));
assertEquals(6, trip.pairwiseDebts().size());
assertTrue(trip.pairwiseDebts().contains(new Transfer("asha", "bala", 56667)));
trip.settle("dev", "asha", 100000);
out.blank().line("After dev pays asha Rs 1000.00 (Rs 100.00 more than dev owes)");
out.line(Fixtures.describe(trip.balances()));
assertEquals(10000L, trip.balances().get("dev"));
assertTrue(trip.isBalanced());
out.blank().line("Now chitra and dev follow the simplified plan");
List<Transfer> plan = trip.simplifiedDebts(new OptimalDebtSimplifier());
plan.forEach(t -> out.line(" " + t));
for (Transfer t : plan) {
trip.settle(t.from(), t.to(), t.paise());
}
out.blank().line("After the plan");
out.line(Fixtures.describe(trip.balances()));
out.line("net balances all zero: " + trip.balances().values().stream().allMatch(v -> v == 0));
out.line("pair view still lists " + trip.pairwiseDebts().size() + " debts, because the plan paid net amounts, not the original pairs:");
trip.pairwiseDebts().forEach(t -> out.line(" " + t));
assertTrue(trip.balances().values().stream().allMatch(v -> v == 0));
assertEquals(5, trip.pairwiseDebts().size());
// the two views never disagree about a person's total: each pair debt nets out to the same balance
Map<String, Long> fromPairs = Fixtures.netFromPairs(trip.pairwiseDebts());
out.line("each person's pair debts add up to their net balance: "
+ trip.balances().keySet().stream().allMatch(u -> fromPairs.getOrDefault(u, 0L).equals(trip.balances().get(u))));
trip.balances().keySet().forEach(u -> assertEquals(trip.balances().get(u), fromPairs.getOrDefault(u, 0L)));
out.flush();
}
@Test
void ledgerIsJustAFoldOverTheEvents() {
Group trip = Fixtures.goaTrip();
trip.settle("chitra", "asha", 100000);
Ledger replay = new Ledger();
trip.expenses().forEach(replay::apply);
trip.settlements().forEach(replay::apply);
Transcript out = Transcript.start("05b-replay.txt", "The ledger is derived: replaying the log rebuilds it exactly");
out.line("expenses replayed: " + trip.expenses().size());
out.line("settlements replayed: " + trip.settlements().size());
out.line("net balances equal: " + replay.net().equals(Map.copyOf(trip.balances())));
out.line("pairwise debts equal: " + replay.pairwiseDebts().equals(trip.pairwiseDebts()));
assertEquals(Map.copyOf(trip.balances()), Map.copyOf(replay.net()));
assertEquals(trip.pairwiseDebts(), replay.pairwiseDebts());
out.flush();
}
}
@@ -0,0 +1,155 @@
package com.ankurm.interviewlab.splitwise;
import com.ankurm.interviewlab.splitwise.support.Fixtures;
import com.ankurm.interviewlab.splitwise.support.Transcript;
import org.junit.jupiter.api.Test;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.SplittableRandom;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
class SimplifyTest {
private final DebtSimplifier greedy = new GreedyDebtSimplifier();
private final DebtSimplifier optimal = new OptimalDebtSimplifier();
/** Applies the payments to the balances and returns what is left over. */
private static Map<String, Long> afterPaying(Map<String, Long> net, List<Transfer> transfers) {
Map<String, Long> left = new LinkedHashMap<>(net);
for (Transfer t : transfers) {
left.merge(t.from(), t.paise(), Long::sum);
left.merge(t.to(), -t.paise(), Long::sum);
}
return left;
}
private static Map<String, Long> balances(Object... pairs) {
Map<String, Long> map = new LinkedHashMap<>();
for (int i = 0; i < pairs.length; i += 2) {
map.put((String) pairs[i], ((Number) pairs[i + 1]).longValue() * 100);
}
return map;
}
/** Independent check: the classic backtracking search, no bitmasks, for the minimum number of payments. */
private static int backtrack(long[] debts, int start) {
while (start < debts.length && debts[start] == 0) {
start++;
}
if (start == debts.length) {
return 0;
}
int best = Integer.MAX_VALUE;
for (int i = start + 1; i < debts.length; i++) {
if (debts[i] * debts[start] < 0) {
debts[i] += debts[start];
best = Math.min(best, 1 + backtrack(debts, start + 1));
debts[i] -= debts[start];
}
}
return best;
}
@Test
void tripAndTheCaseWhereGreedyIsNotMinimal() {
Transcript out = Transcript.start("04-simplify.txt", "Simplifying debts: pairwise vs greedy vs exact");
Group trip = Fixtures.goaTrip();
out.line("Goa trip: " + trip.pairwiseDebts().size() + " pairwise payments, "
+ trip.simplifiedDebts(greedy).size() + " greedy, " + trip.simplifiedDebts(optimal).size() + " exact");
assertEquals(6, trip.pairwiseDebts().size());
assertEquals(3, trip.simplifiedDebts(greedy).size());
assertEquals(3, trip.simplifiedDebts(optimal).size());
Map<String, Long> net = balances("a", 4, "b", 3, "c", 3, "d", -4, "e", -6);
List<Transfer> g = greedy.simplify(net);
List<Transfer> o = optimal.simplify(net);
out.blank().line("Balances (Rs): a +4, b +3, c +3, d -4, e -6");
out.line("greedy: " + g.size() + " payments");
g.forEach(t -> out.line(" " + t));
out.line("exact: " + o.size() + " payments");
o.forEach(t -> out.line(" " + t));
out.line("why: {a, d} cancel exactly (+4 -4) and {b, c, e} cancel exactly (+3 +3 -6), so two separate groups need 1 + 2 = 3 payments");
assertEquals(4, g.size());
assertEquals(3, o.size());
assertTrue(afterPaying(net, g).values().stream().allMatch(v -> v == 0));
assertTrue(afterPaying(net, o).values().stream().allMatch(v -> v == 0));
out.flush();
}
@Test
void randomBalancesCrossCheckedAgainstBacktracking() {
Transcript out = Transcript.start("04b-simplify-random.txt", "1500 seeded random zero-sum balance sets, up to 9 people");
SplittableRandom random = new SplittableRandom(465);
int cases = 1500;
int greedyWorse = 0;
int largestGap = 0;
for (int c = 0; c < cases; c++) {
Map<String, Long> net = new LinkedHashMap<>();
int groups = 1 + random.nextInt(3);
int person = 0;
for (int g = 0; g < groups; g++) {
int size = 2 + random.nextInt(3);
long running = 0;
for (int i = 0; i < size - 1; i++) {
long amount = (random.nextInt(2001) - 1000) * 100L;
net.put("u" + person++, amount);
running += amount;
}
net.put("u" + person++, -running);
}
long[] debts = net.values().stream().mapToLong(Long::longValue).toArray();
int nonZero = (int) java.util.Arrays.stream(debts).filter(v -> v != 0).count();
List<Transfer> g = greedy.simplify(net);
List<Transfer> o = optimal.simplify(net);
assertTrue(afterPaying(net, g).values().stream().allMatch(v -> v == 0), "greedy must settle everyone");
assertTrue(afterPaying(net, o).values().stream().allMatch(v -> v == 0), "exact must settle everyone");
assertTrue(g.size() <= Math.max(nonZero - 1, 0), "greedy never needs more than n - 1");
assertEquals(backtrack(debts.clone(), 0), o.size(), "exact search agrees with backtracking");
assertTrue(o.size() <= g.size());
if (g.size() > o.size()) {
greedyWorse++;
largestGap = Math.max(largestGap, g.size() - o.size());
}
}
out.line("cases: " + cases);
out.line("every case: both simplifiers leave every balance at exactly zero");
out.line("every case: greedy uses at most (people with a balance) - 1 payments");
out.line("every case: the exact simplifier's count equals an independent backtracking search");
out.line("cases where greedy used more payments than exact: " + greedyWorse + " of " + cases);
out.line("largest difference: " + largestGap + " payment(s)");
assertTrue(greedyWorse > 0);
out.flush();
}
@Test
void exactSearchCostGrowsWithPeople() {
Transcript out = Transcript.start("04c-simplify-cost.txt", "Exact search cost (timing dependent: figures differ from run to run)");
SplittableRandom random = new SplittableRandom(7);
for (int n : new int[]{10, 14, 18, 20}) {
Map<String, Long> net = new LinkedHashMap<>();
long running = 0;
for (int i = 0; i < n - 1; i++) {
long amount = (1 + random.nextInt(900)) * 100L * (random.nextBoolean() ? 1 : -1);
net.put("u" + i, amount);
running += amount;
}
net.put("u" + (n - 1), -running);
long start = System.nanoTime();
List<Transfer> o = optimal.simplify(net);
long ms = (System.nanoTime() - start) / 1_000_000;
long gMs0 = System.nanoTime();
List<Transfer> g = greedy.simplify(net);
long gMicros = (System.nanoTime() - gMs0) / 1_000;
out.line(String.format("people %2d: exact %d payments in about %d ms, greedy %d payments in about %d microseconds",
n, o.size(), ms, g.size(), gMicros));
assertTrue(afterPaying(net, o).values().stream().allMatch(v -> v == 0));
}
assertTrue(true);
out.flush();
}
}
@@ -0,0 +1,81 @@
package com.ankurm.interviewlab.splitwise;
import com.ankurm.interviewlab.splitwise.support.Fixtures;
import com.ankurm.interviewlab.splitwise.support.Transcript;
import org.junit.jupiter.api.Test;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.function.Executable;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class ValidationTest {
private final Transcript out = Transcript.start("03-validation.txt", "Bad input is rejected before it touches the ledger");
private void rejected(String label, Class<? extends Throwable> type, String expectedMessage, Executable action) {
Throwable t = assertThrows(type, action);
out.line(String.format("%-34s -> %s: %s", label, t.getClass().getSimpleName(), t.getMessage()));
assertEquals(expectedMessage, t.getMessage());
}
@Test
void rejectsBadSplitsAndBadRequests() {
Group trip = Fixtures.goaTrip();
Map<String, Long> before = trip.balances();
int expensesBefore = trip.expenses().size();
rejected("exact amounts too small", InvalidSplitException.class,
"exact amounts add up to Rs 90.00 but the expense is Rs 100.00",
() -> trip.addExpense("Snacks", "asha", Money.ofRupees("100.00"),
new ExactSplit(Map.of("asha", Money.ofRupees("50.00"), "bala", Money.ofRupees("40.00")))));
rejected("percentages add up to 99.99", InvalidSplitException.class,
"percentages add up to 99.99 but must add up to 100",
() -> new PercentSplit(Fixtures.percents("asha", "33.33", "bala", "33.33", "chitra", "33.33")));
rejected("percentage with 3 decimal places", InvalidSplitException.class,
"percent for asha has more than 2 decimal places: 33.333",
() -> new PercentSplit(Fixtures.percents("asha", "33.333", "bala", "66.667")));
rejected("zero shares", InvalidSplitException.class,
"shares for bala must be positive",
() -> new ShareSplit(Fixtures.shares("asha", 1, "bala", 0)));
rejected("same person listed twice", InvalidSplitException.class,
"duplicate participant in [asha, asha]",
() -> new EqualSplit(List.of("asha", "asha")));
rejected("nobody to split with", InvalidSplitException.class,
"an equal split needs at least one participant",
() -> new EqualSplit(List.of()));
rejected("participant outside the group", IllegalArgumentException.class,
"esha is not a member of group Goa trip",
() -> trip.addExpense("Taxi", "asha", 5000, new EqualSplit(List.of("asha", "esha"))));
rejected("payer outside the group", IllegalArgumentException.class,
"esha is not a member of group Goa trip",
() -> trip.addExpense("Taxi", "esha", 5000, new EqualSplit(List.of("asha", "bala"))));
rejected("zero-rupee expense", IllegalArgumentException.class,
"an expense must be positive, got Rs 0.00",
() -> trip.addExpense("Nothing", "asha", 0, new EqualSplit(List.of("asha", "bala"))));
rejected("paying yourself", IllegalArgumentException.class,
"asha cannot pay themselves",
() -> trip.settle("asha", "asha", 100));
rejected("amount with three decimals", IllegalArgumentException.class,
"not a whole number of paise: 10.005",
() -> Money.ofRupees("10.005"));
out.blank().line("After eleven rejected requests: " + trip.expenses().size() + " expenses, balances unchanged = " + before.equals(trip.balances()));
assertEquals(before, trip.balances());
assertEquals(expensesBefore, trip.expenses().size());
assertTrue(trip.isBalanced());
out.flush();
}
@Test
void exactSplitKeepsInsertionOrder() {
Map<String, Long> amounts = new LinkedHashMap<>();
amounts.put("dev", 100L);
amounts.put("asha", 200L);
assertEquals(List.of("dev", "asha"), List.copyOf(new ExactSplit(amounts).split(300).keySet()));
}
}
@@ -0,0 +1,83 @@
package com.ankurm.interviewlab.splitwise.support;
import com.ankurm.interviewlab.splitwise.EqualSplit;
import com.ankurm.interviewlab.splitwise.ExactSplit;
import com.ankurm.interviewlab.splitwise.Expense;
import com.ankurm.interviewlab.splitwise.Group;
import com.ankurm.interviewlab.splitwise.Money;
import com.ankurm.interviewlab.splitwise.PercentSplit;
import com.ankurm.interviewlab.splitwise.ShareSplit;
import com.ankurm.interviewlab.splitwise.SplitwiseService;
import java.math.BigDecimal;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public final class Fixtures {
private Fixtures() {
}
public static final List<String> FRIENDS = List.of("asha", "bala", "chitra", "dev");
/** The four-friend Goa trip used throughout the article: five expenses, four different split strategies. */
public static Group goaTrip() {
SplitwiseService service = new SplitwiseService();
FRIENDS.forEach(id -> service.registerUser(id, id));
Group trip = service.createGroup("goa", "Goa trip", FRIENDS);
trip.addExpense("Hotel (equal)", "asha", Money.ofRupees("12000.00"), new EqualSplit(FRIENDS));
trip.addExpense("Dinner (equal, 3 people)", "bala", Money.ofRupees("100.00"), new EqualSplit(List.of("asha", "bala", "chitra")));
Map<String, Long> cab = new LinkedHashMap<>();
cab.put("asha", Money.ofRupees("300.00"));
cab.put("bala", Money.ofRupees("200.00"));
cab.put("chitra", Money.ofRupees("100.00"));
cab.put("dev", Money.ofRupees("300.00"));
trip.addExpense("Cab (exact)", "chitra", Money.ofRupees("900.00"), new ExactSplit(cab));
trip.addExpense("Scuba (percent)", "dev", Money.ofRupees("4000.00"), new PercentSplit(percents(
"asha", "40", "bala", "10", "chitra", "10", "dev", "40")));
trip.addExpense("Groceries (shares 2:1:1)", "asha", Money.ofRupees("1000.00"), new ShareSplit(shares(
"asha", 2, "bala", 1, "chitra", 1)));
return trip;
}
public static Map<String, BigDecimal> percents(String... pairs) {
Map<String, BigDecimal> map = new LinkedHashMap<>();
for (int i = 0; i < pairs.length; i += 2) {
map.put(pairs[i], new BigDecimal(pairs[i + 1]));
}
return map;
}
public static Map<String, Integer> shares(Object... pairs) {
Map<String, Integer> map = new LinkedHashMap<>();
for (int i = 0; i < pairs.length; i += 2) {
map.put((String) pairs[i], (Integer) pairs[i + 1]);
}
return map;
}
/** Each person's net balance recomputed from the pair view: payments they are owed minus payments they owe. */
public static Map<String, Long> netFromPairs(List<com.ankurm.interviewlab.splitwise.Transfer> pairs) {
Map<String, Long> net = new LinkedHashMap<>();
for (com.ankurm.interviewlab.splitwise.Transfer t : pairs) {
net.merge(t.to(), t.paise(), Long::sum);
net.merge(t.from(), -t.paise(), Long::sum);
}
return net;
}
public static String describe(Expense e) {
String shares = e.shares().entrySet().stream()
.map(en -> en.getKey() + "=" + Money.format(en.getValue()))
.collect(Collectors.joining(" "));
return String.format("#%d %-26s paid by %-7s %11s %s", e.id(), e.description(), e.paidBy(), Money.format(e.totalPaise()), shares);
}
public static String describe(Map<String, Long> balances) {
return balances.entrySet().stream()
.map(en -> String.format("%-7s %12s", en.getKey(), Money.format(en.getValue())))
.collect(Collectors.joining("\n"));
}
}
@@ -0,0 +1,43 @@
package com.ankurm.interviewlab.splitwise.support;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
/** Writes output/NN-*.txt while the calling test asserts the same numbers it prints. */
public final class Transcript {
private final Path path;
private final List<String> lines = new ArrayList<>();
private Transcript(Path path, String header) {
this.path = path;
lines.add(header);
lines.add("=".repeat(Math.min(header.length(), 100)));
lines.add("");
}
public static Transcript start(String fileName, String header) {
Path dir = Path.of("output");
try {
Files.createDirectories(dir);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return new Transcript(dir.resolve(fileName), header);
}
public Transcript line(String text) { lines.add(text); return this; }
public Transcript blank() { lines.add(""); return this; }
public void flush() {
try {
Files.write(path, (String.join("\n", lines) + "\n").getBytes(StandardCharsets.UTF_8));
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}