平均分担成本

qvsjd97n  于 2021-09-13  发布在  Java
关注(0)|答案(1)|浏览(388)

下面的问题是:我有很多人想分担一些东西的成本。例如一次旅行。每个人都要付一部分钱,最后应该计算出谁要花多少钱给谁,这样每个人都是零。为此,我们有以下值

const total = 900;
const should = 150;
let persons = [
  {
    name: "mark",
    total: 100,
  },
  {
    name: "steve",
    total: 300,
  },
  {
    name: "bill",
    total: 130,
  },
  {
    name: "jeff",
    total: 70,
  },
  {
    name: "larry",
    total: 220,
  },
  {
    name: "jack",
    total: 80,
  },
];

我首先计算每个参与者的差异:

persons = persons.map((person) => {
  let difference = should - person.total;
  return { ...person, difference };
});

但在那之后我不知道该怎么办。结果应该是这样的(伪):

Jeff to Steve: 80
Jack to Steve: 70
Mark to Larry: 20
Bill to Larry: 50

这个案子甚至很简单。也可能是一个人不得不把钱给其他几个人。我也不知道如何用谷歌搜索。有人给我一个关于如何实现这一点的提示吗?或者在哪里可以找到可以帮助我的信息?

8tntrjer

8tntrjer1#

这有点难看,但这将循环通过所有支付不够的人,然后找到支付过高的人,并描述他们之间的“转移”。

const total = 900;
let persons = [
  { name: 'mark', total: 100 },
  { name: 'steve', total: 300 },
  { name: 'bill', total: 130 },
  { name: 'jeff', total: 70 },
  { name: 'larry', total: 220 },
  { name: 'jack', total: 80 }
];
const should = 150 // total / persons.length;
persons = persons.map(x => ({ ...x, diff: should - x.total }));
const ops = [];

persons.forEach(x => {
  // if person hasn't paid enough...
  while (x.diff > 0) {
    // find first person who overpaid...
    const payee = persons.find(y => y.diff < 0);
    // figure out how much needs to be paid...
    const payment = Math.min(x.diff, -payee.diff);
    x.diff -= payment; // subtract from payer
    payee.diff += payment; // add to payee
    ops.push(`${x.name} to ${payee.name}: ${payment}`);
  }
  return x;
});
console.log(ops.join('\n'));

相关问题