If you live with some friends in a shared house then you’ve probably got into the situation where you’ve all paid various bills, and you need to settle up. This R code finds an efficient number of transactions between you. There can be any number of people involved, so long as ‘names’ and ‘payments’ are the same length. Enter the total each person has paid, rather than each bill separately.

names <- c("A", "B", "C", "D", "E", "F") payments <- c(12, 10, 50, 40, 28, 28) n <- length(names) owed <- payments - mean(payments) credits <- ifelse(owed > 0, owed, 0) debts <- ifelse(owed < 0, -owed, 0) sm <- matrix(rep(1, n^2), n, n) y <- 1 while (y <= n) { settles <- NULL x <- 1 debt <- debts[y] while (x <= n) { settles[x] <- ifelse(debt > credits[x], credits[x], debt) debt <- debt - settles[x] x <- x + 1 } credits <- credits - settles sm[y,] <- settles y <- y + 1 } sm <- round(sm, 2) y <- 1 while (y <= n) { x <- 1 while (x <= n) { sm[x,y] <- ifelse(sm[x,y] == 0, "x", paste(names[x], "owes", names[y], sm[x,y])) x <- x + 1 } y <- y + 1 } as.list(sm[sm != "x"])

Advertisements