I'm trying to write a program where users are able to split mixed bills and find out who has to pay how much, as well as each user should know how much owes to which user/users, number of users can be as much as users wishes to have,
for instance:
user a = 100$
user b = 25$
user c = 50$
user d = 75$
user e = 250$
total equals 500$ and each user should pay 100$, hence the program should calculate as:
user b has to pay: 75$ to user a, user c has to pay: 50$ to user e, user d has to pay: 25$ to user e,
looking forward for any help.
This is how I would do it, I wrote it quickly it can be refactored.
let users = [{name:"A person",amount:100},{name:"B Person",amount:25},{name:"C Person",amount:50},{name:"D Person",amount:75},{name:"E Person",amount:250}]
let calculatedAmounts = []
let total = 0;
let amountPerPerson =0
//calculate all the paid amount
for (let x of users){
total += x.amount
}
//get the avrage
amountPerPerson = total/users.length
console.log("each person should pay : " + amountPerPerson)
//push the amount that should be paid by everyone to an array
for (let x of users){
calculatedAmounts.push({name:x.name,amount:x.amount - amountPerPerson})}
let whoPaidWho = []
//Loop to make sure everyone got paid.
while (Math.round(Math.max(...calculatedAmounts.map(item => item.amount))) !== 0){
let sorted = calculatedAmounts.sort((a,b) => a.amount - b.amount);
i = 0;
let value = sorted[sorted.length - 1].amount + sorted[i].amount;
whoPaidWho.push(sorted[i].name + " should give to " + sorted[sorted.length - 1].name +" this much : "+ Math.abs(sorted[i].amount) )
sorted[i].amount = 0
sorted[sorted.length - 1].amount = value
calculatedAmounts=[...sorted]
}
console.log(whoPaidWho)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.