Skip to content
Advertisement

Javascript Coin changing / Change making algorithm

So I’ve been trying to create a program in Javascript/jQuery that splits an amount of money into the smallest amount of dollar bills. So far the program only works with one bill, and I’m not too sure how to implement the rest and need a push in the right direction here.

JavaScript

If I run this with money = 89; it will return 100 because that’s the closest bill that can pay for $89, but I want it to return 50 + 20 + 20 so it will work with money = *anything*.

EDIT: After comments I’ve now come so far:

JavaScript

Advertisement

Answer

As stated in the comments, it might be a variant of the Knapsack problem.

Edit : it’s actually known as coin changing or change making problem.

If I understood well, you want a minimal solution to this inequation :

a1x1 + a2x2 + … + anxn >= b

The sum must be as close as possible to b with as few bills as possible.

Brute force recursive solution

  • Get all possible combination of bills that answer your inequation
  • Find the ones which sum is the closest to the solution
  • Find the solution using the less bills

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement