This is kind of more generic question, isn\'t language-specific. More about idea and algorithm to use.
The system is as follows:
It registers small loans bet
I found a practical solution which I implemented in Excel:
find out who ows the most
let that person pay the complete amount he ows to the one who should get the most
that makes the first person zero
repeat this proces taken into account that one of (n-1) persons has a changed amount
It should result in a maximum of (n-1) transfers and the nice thing about it is that no one is doing more than one payment. Take the (modified) example of jrandomhacker:
a=-5 b=25 c=-20 d=3 e=-2 f=-1 (sum should be zero!)
c -> b 20. result: a=-5 b=5 c=0 d=3 e=-2 f=-1
a -> b 5 result: a=0 b=0 c=0 d=3 e=-2 f=-1
e -> d 2 result a=0 b=0 c=0 d=1 e=0 f=-1
f -> d 1
Now, everyone is satisfied and no one is bothered by making two or more payments. As you can see, it is possible that one person recieves more than one payment (person d in this example).