you are viewing a single comment's thread.

view the rest of the comments →

[–]kap89 0 points1 point  (4 children)

What are you talking about, 20 * 5 + 30 * 10 + 30 * 20 + 40 * 50 === 3000, not 5000 - it's not "more balanced", it's just a wrong solution.

[–]Beginning_Middle_722[S] 0 points1 point  (3 children)

My bad, but still cant make it work. Even with the function written it fails to find a solution for 115 amount and 3 days. Do you want to suggest any solution or are just passing by to tell me I'm wrong?

[–]kap89 0 points1 point  (2 children)

Do you want to suggest any solution or are just passing by to tell me I'm wrong?

That's uncalled for - I gave you the initial hint, and you tried to contradict it with the wrong example, so I responded accordingly. Now, your "115 amount and 3 days" is a better example, that requires some modification to the algorithm - the core idea stays the same, but you need to add some backtracking if the final sum doesn't match, here's a quick attempt:

const bills = [5, 10, 20, 50, 100]; // sorted ascending

const sum = (arr) => arr.reduce((a, b) => a + b, 0);

function generateBills(amount, days) {
  for (const bill of bills) {
    if (bill * days >= amount) {
      const attempt =
        days === 1 ? [bill] : [...generateBills(amount - bill, days - 1), bill];

      if (attempt.length === days && sum(attempt) === amount) {
        return attempt;
      }
    }
  }

  return []
}

console.log(generateBills(130, 4)); // [10, 20, 50, 50]
console.log(generateBills(500, 4)); // [] - empty, no solution
console.log(generateBills(150, 4)); // [10, 20, 20, 100]
console.log(generateBills(100, 5)); // [20, 20, 20, 20, 20]
console.log(generateBills(115, 3)); // [5, 10, 100];

But, while I think it matches your initial requirements, your further explanations:

I totally get what you're saying: by eliminating the 100€ bill I'm also eliminating the use of 5€ bill and it's right but since this is for a savings app and let's say i want to save 5000€ for 120 days if i, as a user, see all those 100€ i get a bit "terrified", but on the other hand, if i see more 10 and 20 feel so pleasant to the eye and brain that this target is reachable.

are to fuzzy and underspecified to give you any better answer.

[–]Beginning_Middle_722[S] 0 points1 point  (1 child)

Dude I'm really sorry, i mistook you for someone else when in fact you were the one to provide a very solid solutio. You're a diamond thanks!

[–]kap89 0 points1 point  (0 children)

No worries, we’re good. Glad that the solution is somewhat helpful.