Skip to content

Instantly share code, notes, and snippets.

@ayal
Created February 14, 2020 12:07
Show Gist options
  • Save ayal/2335444f613a7875097ab15ab6b1b1c7 to your computer and use it in GitHub Desktop.
Save ayal/2335444f613a7875097ab15ab6b1b1c7 to your computer and use it in GitHub Desktop.
balance
var userSums = [{name: 'ayal', sum: 400}, {name: 'tomer', sum: 300}, {name: 'guy', sum: 250}, {name: 'ronni', sum: 0}, {name: 'max', sum: 0}];
var sum = userSums.reduce((acc,u)=>acc+u.sum,0);
var usum = sum / userSums.length;
userSums.map(x=>(x.balance = x.sum - usum) && (x.gotgave = 0));
var balanceUsers = (u1,u2)=> {
if (u1.balance < 0 && u2.balance > 0) {
// u1 pays u2
let topay = 0;
//debugger;
if (Math.abs(u1.balance) >= u2.balance) {
topay = u2.balance;
}
else {
topay = -u1.balance;
}
console.log(u1.name, 'pays', u2.name, topay);
u1.balance += topay;
u1.gotgave -= topay;
u2.balance -= topay;
u2.gotgave += topay;
}
if (u2.balance < 0 && u1.balance > 0) {
balanceUsers(u2, u1);
}
};
var balanceUser = (u) => {
for (let userSum of userSums) {
balanceUsers(u, userSum)
}
}
console.log('every one should pay', usum);
for (let userSum of userSums) {
balanceUser(userSum);
}
console.log(userSums);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment