【问题标题】:Sharing costs evenly平均分摊成本
【发布时间】:2021-09-19 08:11:54
【问题描述】:

以下问题:我有很多人想为某事分摊成本。例如一次旅行。每个人都支付一部分,最后应该计算谁必须花多少钱给谁,这样每个人都为零。为此,我们有以下值

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

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

【问题讨论】:

    标签: javascript algorithm math


    【解决方案1】:

    有点难看,但是这会循环遍历所有未付足够的人,然后会找到多付的人并描述他们之间的“转移”。

    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'));

    【讨论】:

    • 太棒了!谢谢!
    猜你喜欢
    • 1970-01-01
    • 2018-02-13
    • 2011-11-12
    • 2017-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-20
    • 1970-01-01
    相关资源
    最近更新 更多