我正在尝试为我的社区编写一个简单的程序。 我们是3个人,每周都去买杂货。 在本周末,我们聚在一起做一些会计,以便每个人花费相同的金额。
我想要的是一个输出如下内容的程序:
“A人欠人B的钱
人A欠人C的钱<“
如果有人需要提供或者有人获得金钱,我可以计算一下。 我这样做(翻译成js伪代码):
var a // ammount of money person a spend this week
var b // same for pers b
var c // you guess it
var fa // the factor person a was involved in eating the food (dont ask why)
var fb // this will be range 0 - 1
var fc // and these 3 need to add up to 1
var sum = a + b + c
var x = sum / 3
//the ammount each person should have paid
var sa = x * fa
var sb = x * fb
var sc = x * fc
/*the resulting numbers tell if a person still needs to pay some money
or gets money and how much (negative or positive)*/
var ra = a - sa
var rb = b - sb
var rc = c - sc
有没有办法从这个结果到我前面描述的输出而没有覆盖所有情况(如人少付钱,b人太多,人c太多等)和条件?
答案 0 :(得分:3)
解决方案是在不足者和超支者之间划分小组。
对于每一对一个吊杆和一个吊杆,它们之间所欠的金额是承销人的欠费金额,或超支的超支金额,以较小者为准(吊杆不能超过金额)他们支付不足,而且超支的收入不应超过他们超支的金额。)
请记住,这不适用于3人以上。任何超过3,你只需要汇集债务并将它们分开。
在三人案例中,有四种可能的情况:
我的第二段中的策略涵盖了所有支出/超支关系(在每对人之间采取较小的数额)。如果你愿意,你可以检查那些既没有支出也没有超支的人(我已经在下面提到了)。
function calcDebts(differentials) {
const underspenders = differentials.filter(d => d.amount < 0);
const overspenders = differentials.filter(d => d.amount > 0);
const rightonspenders = differentials.filter(d => d.amount === 0);
for (let ros of rightonspenders) {
console.log(`${ros.name} owes nothing`);
}
for (let us of underspenders) {
for (let os of overspenders) {
console.log(`${us.name} owes ${os.name} ${Math.min(-us.amount, os.amount)}`);
}
}
}
console.log('one person underspent');
calcDebts([
{ name: 'a', amount: -3.25 },
{ name: 'b', amount: 1.5 },
{ name: 'c', amount: 1.75 }
]);
console.log('one person overspent');
calcDebts([
{ name: 'a', amount: 2.25 },
{ name: 'b', amount: -1.5 },
{ name: 'c', amount: -0.75 }
]);
console.log('one person paid exactly the right amount');
calcDebts([
{ name: 'a', amount: 1.25 },
{ name: 'b', amount: 0 },
{ name: 'c', amount: -1.25 }
]);
console.log('all paid the right amount');
calcDebts([
{ name: 'a', amount: 0 },
{ name: 'b', amount: 0 },
{ name: 'c', amount: 0 }
]);
&#13;